diff --git a/TODO.md b/TODO.md index 877c45e..1c717e1 100644 --- a/TODO.md +++ b/TODO.md @@ -45,7 +45,6 @@ with modern equivalent. Key updates are: Next steps are: * review function signatures in the public API -* replace code that uses QUtil::make_shared_cstr etc Except for the above, prefer to make modernization changes as part of other updates. diff --git a/compare-for-test/qpdf-test-compare.cc b/compare-for-test/qpdf-test-compare.cc index 5d3e6e2..04f3b80 100644 --- a/compare-for-test/qpdf-test-compare.cc +++ b/compare-for-test/qpdf-test-compare.cc @@ -13,18 +13,14 @@ static char const* whoami = nullptr; void usage() { - std::cerr << "Usage: " << whoami << " actual expected" << std::endl - << R"(Where "actual" is the actual output and "expected" is the expected)" - << std::endl - << "output of a test, compare the two PDF files. The files are considered" - << std::endl - << "to match if all their objects are identical except that, if a stream is" - << std::endl - << "compressed with FlateDecode, the uncompressed data must match." << std::endl - << std::endl - << "If the files match, the output is the expected file. Otherwise, it is" - << std::endl - << "the actual file. Read comments in the code for rationale." << std::endl; + std::cerr << "Usage: " << whoami << " actual expected" << '\n' + << R"(Where "actual" is the actual output and "expected" is the expected)" << '\n' + << "output of a test, compare the two PDF files. The files are considered" << '\n' + << "to match if all their objects are identical except that, if a stream is" << '\n' + << "compressed with FlateDecode, the uncompressed data must match." << '\n' + << '\n' + << "If the files match, the output is the expected file. Otherwise, it is" << '\n' + << "the actual file. Read comments in the code for rationale." << '\n'; exit(2); } @@ -187,7 +183,7 @@ main(int argc, char* argv[]) } if ((argc == 2) && (strcmp(argv[1], "--version") == 0)) { - std::cout << whoami << " from qpdf version " << QPDF::QPDFVersion() << std::endl; + std::cout << whoami << " from qpdf version " << QPDF::QPDFVersion() << '\n'; exit(0); } @@ -211,7 +207,7 @@ main(int argc, char* argv[]) to_output = expected; } else { if (show_why) { - std::cerr << difference << std::endl; + std::cerr << difference << '\n'; exit(2); } // The files differ; write the actual file. If it is determined that the actual file @@ -237,7 +233,7 @@ main(int argc, char* argv[]) exit(2); } } catch (std::exception& e) { - std::cerr << whoami << ": " << e.what() << std::endl; + std::cerr << whoami << ": " << e.what() << '\n'; exit(2); } return 0; diff --git a/examples/pdf-attach-file.cc b/examples/pdf-attach-file.cc index be3ca25..6f3659b 100644 --- a/examples/pdf-attach-file.cc +++ b/examples/pdf-attach-file.cc @@ -19,15 +19,15 @@ static char const* whoami = nullptr; static void usage(std::string const& msg) { - std::cerr << msg << std::endl - << std::endl - << "Usage: " << whoami << " options" << std::endl - << "Options:" << std::endl - << " --infile infile.pdf" << std::endl - << " --outfile outfile.pdf" << std::endl - << " --attachment attachment" << std::endl - << " [--password infile-password]" << std::endl - << " [--mimetype attachment mime type]" << std::endl; + std::cerr << msg << '\n' + << '\n' + << "Usage: " << whoami << " options\n" + << "Options:\n" + << " --infile infile.pdf\n" + << " --outfile outfile.pdf\n" + << " --attachment attachment\n" + << " [--password infile-password]\n" + << " [--mimetype attachment mime type]\n"; exit(2); } @@ -69,7 +69,7 @@ process( // Create a file spec. std::string key = QUtil::path_basename(attachment); - std::cout << whoami << ": attaching " << attachment << " as " << key << std::endl; + std::cout << whoami << ": attaching " << attachment << " as " << key << '\n'; auto fs = QPDFFileSpecObjectHelper::createFileSpec(q, key, attachment); if (mimetype) { @@ -208,7 +208,7 @@ main(int argc, char* argv[]) try { process(infilename, password, attachment, mimetype, outfilename); } catch (std::exception& e) { - std::cerr << whoami << " exception: " << e.what() << std::endl; + std::cerr << whoami << " exception: " << e.what() << '\n'; exit(2); } diff --git a/examples/pdf-bookmarks.cc b/examples/pdf-bookmarks.cc index 87a3b9d..665ac0f 100644 --- a/examples/pdf-bookmarks.cc +++ b/examples/pdf-bookmarks.cc @@ -23,12 +23,12 @@ static std::map page_map; void usage() { - std::cerr << "Usage: " << whoami << " [options] file.pdf [password]" << std::endl - << "Options:" << std::endl - << " --numbers give bookmarks outline-style numbers" << std::endl - << " --lines draw lines to show bookmark hierarchy" << std::endl - << " --show-open indicate whether a bookmark is initially open" << std::endl - << " --show-targets show target if possible" << std::endl; + std::cerr << "Usage: " << whoami << " [options] file.pdf [password]\n" + << "Options:\n" + << " --numbers give bookmarks outline-style numbers\n" + << " --lines draw lines to show bookmark hierarchy\n" + << " --show-open indicate whether a bookmark is initially open\n" + << " --show-targets show target if possible\n"; exit(2); } @@ -74,7 +74,7 @@ show_bookmark_details(QPDFOutlineObjectHelper outline, std::vector numbers) case st_lines: QTC::TC("examples", "pdf-bookmarks lines"); print_lines(numbers); - std::cout << "|" << std::endl; + std::cout << "|\n"; print_lines(numbers); std::cout << "+-+ "; break; @@ -104,7 +104,7 @@ show_bookmark_details(QPDFOutlineObjectHelper outline, std::vector numbers) QPDFObjectHandle dest_page = outline.getDestPage(); if (!dest_page.isNull()) { QTC::TC("examples", "pdf-bookmarks dest"); - if (page_map.count(dest_page)) { + if (page_map.contains(dest_page)) { target = std::to_string(page_map[dest_page]); } } @@ -136,7 +136,7 @@ main(int argc, char* argv[]) whoami = QUtil::getWhoami(argv[0]); if ((argc == 2) && (strcmp(argv[1], "--version") == 0)) { - std::cout << whoami << " version 1.5" << std::endl; + std::cout << whoami << " version 1.5\n"; exit(0); } @@ -185,10 +185,10 @@ main(int argc, char* argv[]) } extract_bookmarks(odh.getTopLevelOutlines(), numbers); } else { - std::cout << filename << " has no bookmarks" << std::endl; + std::cout << filename << " has no bookmarks\n"; } } catch (std::exception& e) { - std::cerr << whoami << " processing file " << filename << ": " << e.what() << std::endl; + std::cerr << whoami << " processing file " << filename << ": " << e.what() << '\n'; exit(2); } diff --git a/examples/pdf-count-strings.cc b/examples/pdf-count-strings.cc index 2b5b557..c262459 100644 --- a/examples/pdf-count-strings.cc +++ b/examples/pdf-count-strings.cc @@ -18,8 +18,8 @@ static char const* whoami = nullptr; void usage() { - std::cerr << "Usage: " << whoami << " infile" << std::endl - << "Applies token filters to infile" << std::endl; + std::cerr << "Usage: " << whoami << " infile\n" + << "Applies token filters to infile\n"; exit(2); } @@ -88,14 +88,14 @@ main(int argc, char* argv[]) } else { // Write output to stdout for even pages. Pl_StdioFile out("stdout", stdout); - std::cout << "% Contents of page " << pageno << std::endl; + std::cout << "% Contents of page " << pageno << '\n'; page.filterContents(&counter, &out); - std::cout << "\n% end " << pageno << std::endl; + std::cout << "\n% end " << pageno << '\n'; } - std::cout << "Page " << pageno << ": strings = " << counter.getCount() << std::endl; + std::cout << "Page " << pageno << ": strings = " << counter.getCount() << '\n'; } } catch (std::exception& e) { - std::cerr << whoami << ": " << e.what() << std::endl; + std::cerr << whoami << ": " << e.what() << '\n'; exit(2); } diff --git a/examples/pdf-create.cc b/examples/pdf-create.cc index c44e5f5..f09d8c4 100644 --- a/examples/pdf-create.cc +++ b/examples/pdf-create.cc @@ -117,8 +117,8 @@ ImageProvider::provideStreamData(QPDFObjGen const&, Pipeline* pipeline) void usage() { - std::cerr << "Usage: " << whoami << " filename" << std::endl - << "Creates a simple PDF and writes it to filename" << std::endl; + std::cerr << "Usage: " << whoami << " filename\n" + << "Creates a simple PDF and writes it to filename\n"; exit(2); } @@ -257,12 +257,12 @@ check( if (!filter.isNameAndEquals(desired_filter)) { this_errors = errors = true; std::cout << "page " << pageno << ": expected filter " << desired_filter - << "; actual filter = " << filter.unparse() << std::endl; + << "; actual filter = " << filter.unparse() << '\n'; } if (!color_space.isNameAndEquals(desired_color_space)) { this_errors = errors = true; std::cout << "page " << pageno << ": expected color space " << desired_color_space - << "; actual color space = " << color_space.unparse() << std::endl; + << "; actual color space = " << color_space.unparse() << '\n'; } if (!this_errors) { @@ -275,7 +275,7 @@ check( std::shared_ptr desired_data(b_p.getBuffer()); if (desired_data->getSize() != actual_data->getSize()) { - std::cout << "page " << pageno << ": image data length mismatch" << std::endl; + std::cout << "page " << pageno << ": image data length mismatch\n"; this_errors = errors = true; } else { // Compare bytes. For JPEG, allow a certain number of the bytes to be off desired by @@ -297,7 +297,7 @@ check( if (mismatches > threshold) { std::cout << "page " << pageno << ": " << desired_color_space << ", " << desired_filter << ": mismatches: " << mismatches << " of " << len - << std::endl; + << '\n'; this_errors = errors = true; } } @@ -308,7 +308,7 @@ check( if (errors) { throw std::logic_error("errors found"); } else { - std::cout << "all checks passed" << std::endl; + std::cout << "all checks passed\n"; } } @@ -366,7 +366,7 @@ main(int argc, char* argv[]) try { create_pdf(filename); } catch (std::exception& e) { - std::cerr << e.what() << std::endl; + std::cerr << e.what() << '\n'; exit(2); } diff --git a/examples/pdf-custom-filter.cc b/examples/pdf-custom-filter.cc index 1a8f14e..2cc4199 100644 --- a/examples/pdf-custom-filter.cc +++ b/examples/pdf-custom-filter.cc @@ -116,7 +116,7 @@ SF_XORDecode::setDecodeParms(QPDFObjectHandle decode_parms) this->key = buf->getBuffer()[0]; return true; } catch (std::exception& e) { - std::cerr << "Error extracting key for /XORDecode: " << e.what() << std::endl; + std::cerr << "Error extracting key for /XORDecode: " << e.what() << '\n'; } return false; } @@ -276,7 +276,7 @@ StreamReplacer::registerStream( // We don't need to process a stream more than once. In this example, we are just iterating // through objects, but if we were doing something like iterating through images on pages, we // might realistically encounter the same stream more than once. - if (this->copied_streams.count(og) > 0) { + if (this->copied_streams.contains(og)) { return; } // Store something in copied_streams so that we don't double-process even in the negative case. @@ -361,15 +361,13 @@ process(char const* infilename, char const* outfilename, bool decode_specialized // For the test suite, use static IDs. w.setStaticID(true); // for testing only w.write(); - std::cout << whoami << ": new file written to " << outfilename << std::endl; + std::cout << whoami << ": new file written to " << outfilename << '\n'; } static void usage() { - std::cerr << "\n" - << "Usage: " << whoami << " [--decode-specialized] infile outfile\n" - << std::endl; + std::cerr << '\n' << "Usage: " << whoami << " [--decode-specialized] infile outfile\n" << '\n'; exit(2); } @@ -404,7 +402,7 @@ main(int argc, char* argv[]) // Do the actual processing. process(infilename, outfilename, decode_specialized); } catch (std::exception& e) { - std::cerr << whoami << ": exception: " << e.what() << std::endl; + std::cerr << whoami << ": exception: " << e.what() << '\n'; exit(2); } diff --git a/examples/pdf-double-page-size.cc b/examples/pdf-double-page-size.cc index 289c4d1..12bd094 100644 --- a/examples/pdf-double-page-size.cc +++ b/examples/pdf-double-page-size.cc @@ -13,8 +13,8 @@ static char const* whoami = nullptr; void usage() { - std::cerr << "Usage: " << whoami << " infile.pdf outfile.pdf [in-password]" << std::endl - << "Double size of all pages in infile.pdf; write output to outfile.pdf" << std::endl; + std::cerr << "Usage: " << whoami << " infile.pdf outfile.pdf [in-password]\n" + << "Double size of all pages in infile.pdf; write output to outfile.pdf\n"; exit(2); } @@ -87,9 +87,9 @@ main(int argc, char* argv[]) w.setStreamDataMode(qpdf_s_uncompress); } w.write(); - std::cout << whoami << ": new file written to " << outfilename << std::endl; + std::cout << whoami << ": new file written to " << outfilename << '\n'; } catch (std::exception& e) { - std::cerr << whoami << " processing file " << infilename << ": " << e.what() << std::endl; + std::cerr << whoami << " processing file " << infilename << ": " << e.what() << '\n'; exit(2); } diff --git a/examples/pdf-filter-tokens.cc b/examples/pdf-filter-tokens.cc index 4a06bcd..12dc178 100644 --- a/examples/pdf-filter-tokens.cc +++ b/examples/pdf-filter-tokens.cc @@ -20,8 +20,8 @@ static char const* whoami = nullptr; void usage() { - std::cerr << "Usage: " << whoami << " infile outfile" << std::endl - << "Applies token filters to infile and writes outfile" << std::endl; + std::cerr << "Usage: " << whoami << " infile outfile\n" + << "Applies token filters to infile and writes outfile\n"; exit(2); } @@ -184,7 +184,7 @@ main(int argc, char* argv[]) w.setQDFMode(true); w.write(); } catch (std::exception& e) { - std::cerr << whoami << ": " << e.what() << std::endl; + std::cerr << whoami << ": " << e.what() << '\n'; exit(2); } diff --git a/examples/pdf-invert-images.cc b/examples/pdf-invert-images.cc index 09e115d..c02627b 100644 --- a/examples/pdf-invert-images.cc +++ b/examples/pdf-invert-images.cc @@ -14,8 +14,8 @@ static char const* whoami = nullptr; void usage() { - std::cerr << "Usage: " << whoami << " infile.pdf outfile.pdf [in-password]" << std::endl - << "Invert some images in infile.pdf; write output to outfile.pdf" << std::endl; + std::cerr << "Usage: " << whoami << " infile.pdf outfile.pdf [in-password]\n" + << "Invert some images in infile.pdf; write output to outfile.pdf\n"; exit(2); } @@ -52,7 +52,7 @@ ImageInverter::registerImage( // Store information about the images based on the object and generation number. Recall that a // single image object may be used more than once, so no need to update the same stream multiple // times. - if (this->copied_images.count(og) > 0) { + if (copied_images.contains(og)) { return; } this->copied_images[og] = image.copyStream(); @@ -137,9 +137,9 @@ main(int argc, char* argv[]) w.setStaticID(true); // for testing only } w.write(); - std::cout << whoami << ": new file written to " << outfilename << std::endl; + std::cout << whoami << ": new file written to " << outfilename << '\n'; } catch (std::exception& e) { - std::cerr << whoami << " processing file " << infilename << ": " << e.what() << std::endl; + std::cerr << whoami << " processing file " << infilename << ": " << e.what() << '\n'; exit(2); } diff --git a/examples/pdf-mod-info.cc b/examples/pdf-mod-info.cc index e97fab9..2fd559a 100644 --- a/examples/pdf-mod-info.cc +++ b/examples/pdf-mod-info.cc @@ -39,7 +39,7 @@ dumpInfoDict(QPDF& pdf, std::ostream& os = std::cout, std::string const& sep = " { val = it.second.unparseResolved(); } - os << it.first.substr(1) << sep << val << std::endl; // skip '/' + os << it.first.substr(1) << sep << val << '\n'; // skip '/' } } } @@ -52,7 +52,7 @@ pdfDumpInfoDict(char const* fname) pdf.processFile(fname); dumpInfoDict(pdf); } catch (std::exception& e) { - std::cerr << e.what() << std::endl; + std::cerr << e.what() << '\n'; exit(2); } } @@ -66,7 +66,7 @@ main(int argc, char* argv[]) whoami = QUtil::getWhoami(argv[0]); if ((argc == 2) && (!strcmp(argv[1], "--version"))) { - std::cout << whoami << " version " << version << std::endl; + std::cout << whoami << " version " << version << '\n'; exit(0); } if ((argc == 3) && (!strcmp(argv[1], "--dump"))) { @@ -90,11 +90,11 @@ main(int argc, char* argv[]) } else if ((!strcmp(argv[i], "--key")) && (++i < argc)) { QTC::TC("examples", "pdf-mod-info -key"); cur_key = argv[i]; - if (!((cur_key.length() > 0) && (cur_key.at(0) == '/'))) { + if (cur_key.empty() || cur_key.at(0) != '/') { cur_key = "/" + cur_key; } Keys[cur_key] = ""; - } else if ((!strcmp(argv[i], "--val")) && (++i < argc)) { + } else if (!strcmp(argv[i], "--val") && ++i < argc) { if (cur_key.empty()) { QTC::TC("examples", "pdf-mod-info usage wrong val"); usage(); @@ -115,7 +115,7 @@ main(int argc, char* argv[]) QTC::TC("examples", "pdf-mod-info in-place"); fl_out = fl_in; } - if (Keys.size() == 0) { + if (Keys.empty()) { QTC::TC("examples", "pdf-mod-info no keys"); usage(); } @@ -141,7 +141,7 @@ main(int argc, char* argv[]) filetrailer.replaceKey("/Info", fileinfo); } } - if (it.second == "") { + if (it.second.empty()) { fileinfo.removeKey(it.first); } else { QPDFObjectHandle elt = fileinfo.newString(it.second); @@ -155,7 +155,7 @@ main(int argc, char* argv[]) w.setStaticID(static_id); // for testing only w.write(); } catch (std::exception& e) { - std::cerr << e.what() << std::endl; + std::cerr << e.what() << '\n'; exit(2); } @@ -164,7 +164,7 @@ main(int argc, char* argv[]) QUtil::os_wrapper( "rename " + fl_tmp + " " + std::string(fl_out), rename(fl_tmp.c_str(), fl_out)); } catch (std::exception& e) { - std::cerr << e.what() << std::endl; + std::cerr << e.what() << '\n'; exit(2); } diff --git a/examples/pdf-name-number-tree.cc b/examples/pdf-name-number-tree.cc index 7701e70..667f973 100644 --- a/examples/pdf-name-number-tree.cc +++ b/examples/pdf-name-number-tree.cc @@ -10,8 +10,8 @@ static char const* whoami = nullptr; void usage() { - std::cerr << "Usage: " << whoami << " outfile.pdf" << std::endl - << "Create some name/number trees and write to a file" << std::endl; + std::cerr << "Usage: " << whoami << " outfile.pdf" << '\n' + << "Create some name/number trees and write to a file\n"; exit(2); } @@ -57,64 +57,63 @@ main(int argc, char* argv[]) name_tree.insert("N", QPDFObjectHandle::newUnicodeString("knight")); auto iter = name_tree.insert("P", QPDFObjectHandle::newUnicodeString("pawn")); // Look at the iterator - std::cout << "just inserted " << iter->first << " -> " << iter->second.unparse() << std::endl; + std::cout << "just inserted " << iter->first << " -> " << iter->second.unparse() << '\n'; --iter; - std::cout << "predecessor: " << iter->first << " -> " << iter->second.unparse() << std::endl; + std::cout << "predecessor: " << iter->first << " -> " << iter->second.unparse() << '\n'; ++iter; ++iter; - std::cout << "successor: " << iter->first << " -> " << iter->second.unparse() << std::endl; + std::cout << "successor: " << iter->first << " -> " << iter->second.unparse() << '\n'; // Use range-for iteration - std::cout << "Name tree items:" << std::endl; + std::cout << "Name tree items:\n"; for (auto i: name_tree) { - std::cout << " " << i.first << " -> " << i.second.unparse() << std::endl; + std::cout << " " << i.first << " -> " << i.second.unparse() << '\n'; } // This is a small tree, so everything will be at the root. We can look at it using dictionary // and array iterators. - std::cout << "Keys in name tree object:" << std::endl; + std::cout << "Keys in name tree object:\n"; QPDFObjectHandle names; for (auto const& i: name_tree_oh.ditems()) { - std::cout << i.first << std::endl; + std::cout << i.first << '\n'; if (i.first == "/Names") { names = i.second; } } // Values in names array: - std::cout << "Values in names:" << std::endl; + std::cout << "Values in names:\n"; for (auto& i: names.aitems()) { - std::cout << " " << i.unparse() << std::endl; + std::cout << " " << i.unparse() << '\n'; } // pre 10.2 API - std::cout << "Has Q?: " << name_tree.hasName("Q") << std::endl; - std::cout << "Has W?: " << name_tree.hasName("W") << std::endl; + std::cout << "Has Q?: " << name_tree.hasName("Q") << '\n'; + std::cout << "Has W?: " << name_tree.hasName("W") << '\n'; QPDFObjectHandle obj; - std::cout << "Found W?: " << name_tree.findObject("W", obj) << std::endl; - std::cout << "Found Q?: " << name_tree.findObject("Q", obj) << std::endl; - std::cout << "Q: " << obj.unparse() << std::endl; + std::cout << "Found W?: " << name_tree.findObject("W", obj) << '\n'; + std::cout << "Found Q?: " << name_tree.findObject("Q", obj) << '\n'; + std::cout << "Q: " << obj.unparse() << '\n'; // 10.2 API iter = name_tree.find("Q"); - std::cout << "Q: " << iter->first << " -> " << iter->second.unparse() << std::endl; + std::cout << "Q: " << iter->first << " -> " << iter->second.unparse() << '\n'; iter = name_tree.find("W"); - std::cout << "W found: " << (iter != name_tree.end()) << std::endl; + std::cout << "W found: " << (iter != name_tree.end()) << '\n'; // Allow find to return predecessor iter = name_tree.find("W", true); - std::cout << "W's predecessor: " << iter->first << " -> " << iter->second.unparse() - << std::endl; + std::cout << "W's predecessor: " << iter->first << " -> " << iter->second.unparse() << '\n'; // We can also remove items - std::cout << "Remove P: " << name_tree.remove("P", &obj) << std::endl; - std::cout << "Value removed: " << obj.unparse() << std::endl; - std::cout << "Has P?: " << name_tree.hasName("P") << std::endl; + std::cout << "Remove P: " << name_tree.remove("P", &obj) << '\n'; + std::cout << "Value removed: " << obj.unparse() << '\n'; + std::cout << "Has P?: " << name_tree.hasName("P") << '\n'; // Or we can remove using an iterator iter = name_tree.find("K"); - std::cout << "Find K: " << iter->second.unparse() << std::endl; + std::cout << "Find K: " << iter->second.unparse() << '\n'; iter.remove(); std::cout << "Iter after removing K: " << iter->first << " -> " << iter->second.unparse() - << std::endl; - std::cout << "Has K?: " << name_tree.hasName("K") << std::endl; + << '\n'; + std::cout << "Has K?: " << name_tree.hasName("K") << '\n'; // Illustrate some more advanced usage using number trees. These calls work for name trees too. @@ -129,14 +128,14 @@ main(int argc, char* argv[]) for (int i = 7; i <= 350; i += 7) { iter2.insertAfter(i, QPDFObjectHandle::newString("-" + std::to_string(i) + "-")); } - std::cout << "Numbers:" << std::endl; + std::cout << "Numbers:\n"; int n = 1; for (auto& i: number_tree) { std::cout << i.first << " -> " << i.second.getUTF8Value(); if (n % 5) { std::cout << ", "; } else { - std::cout << std::endl; + std::cout << '\n'; } ++n; } @@ -151,14 +150,14 @@ main(int argc, char* argv[]) ++iter2; } } - std::cout << "Numbers after filtering:" << std::endl; + std::cout << "Numbers after filtering:\n"; n = 1; for (auto& i: number_tree) { std::cout << i.first << " -> " << i.second.getUTF8Value(); if (n % 5) { std::cout << ", "; } else { - std::cout << std::endl; + std::cout << '\n'; } ++n; } diff --git a/examples/pdf-npages.cc b/examples/pdf-npages.cc index 59598cf..b216204 100644 --- a/examples/pdf-npages.cc +++ b/examples/pdf-npages.cc @@ -10,8 +10,8 @@ static char const* whoami = nullptr; void usage() { - std::cerr << "Usage: " << whoami << " filename" << std::endl - << "Prints the number of pages in filename" << std::endl; + std::cerr << "Usage: " << whoami << " filename\n" + << "Prints the number of pages in filename\n"; exit(2); } @@ -21,7 +21,7 @@ main(int argc, char* argv[]) whoami = QUtil::getWhoami(argv[0]); if ((argc == 2) && (strcmp(argv[1], "--version") == 0)) { - std::cout << whoami << " version 1.3" << std::endl; + std::cout << whoami << " version 1.3\n"; exit(0); } @@ -36,9 +36,9 @@ main(int argc, char* argv[]) QPDFObjectHandle root = pdf.getRoot(); QPDFObjectHandle pages = root.getKey("/Pages"); QPDFObjectHandle count = pages.getKey("/Count"); - std::cout << count.getIntValue() << std::endl; + std::cout << count.getIntValue() << '\n'; } catch (std::exception& e) { - std::cerr << whoami << ": " << e.what() << std::endl; + std::cerr << whoami << ": " << e.what() << '\n'; exit(2); } diff --git a/examples/pdf-overlay-page.cc b/examples/pdf-overlay-page.cc index 97ee802..d4da647 100644 --- a/examples/pdf-overlay-page.cc +++ b/examples/pdf-overlay-page.cc @@ -15,9 +15,8 @@ static char const* whoami = nullptr; void usage() { - std::cerr << "Usage: " << whoami << " infile pagefile outfile" << std::endl - << "Stamp page 1 of pagefile on every page of infile, writing to outfile" - << std::endl; + std::cerr << "Usage: " << whoami << " infile pagefile outfile\n" + << "Stamp page 1 of pagefile on every page of infile, writing to outfile\n"; exit(2); } @@ -81,7 +80,7 @@ main(int argc, char* argv[]) try { stamp_page(infile, stampfile, outfile); } catch (std::exception& e) { - std::cerr << whoami << ": " << e.what() << std::endl; + std::cerr << whoami << ": " << e.what() << '\n'; exit(2); } return 0; diff --git a/examples/pdf-parse-content.cc b/examples/pdf-parse-content.cc index b60693f..fd758f3 100644 --- a/examples/pdf-parse-content.cc +++ b/examples/pdf-parse-content.cc @@ -12,10 +12,10 @@ static char const* whoami = nullptr; void usage() { - std::cerr << "Usage: " << whoami << " filename page-number" << std::endl - << "Prints a dump of the objects in the content streams of the given page." - << std::endl - << "Pages are numbered from 1." << std::endl; + std::cerr << "Usage: " << whoami << " filename page-number\n" + << "Prints a dump of the objects in the content streams of the given page.\n" + << '\n' + << "Pages are numbered from 1.\n"; exit(2); } @@ -31,7 +31,7 @@ class ParserCallbacks: public QPDFObjectHandle::ParserCallbacks void ParserCallbacks::contentSize(size_t size) { - std::cout << "content size: " << size << std::endl; + std::cout << "content size: " << size << '\n'; } void @@ -39,16 +39,16 @@ ParserCallbacks::handleObject(QPDFObjectHandle obj, size_t offset, size_t length { std::cout << obj.getTypeName() << ", offset=" << offset << ", length=" << length << ": "; if (obj.isInlineImage()) { - std::cout << QUtil::hex_encode(obj.getInlineImageValue()) << std::endl; + std::cout << QUtil::hex_encode(obj.getInlineImageValue()) << '\n'; } else { - std::cout << obj.unparse() << std::endl; + std::cout << obj.unparse() << '\n'; } } void ParserCallbacks::handleEOF() { - std::cout << "-EOF-" << std::endl; + std::cout << "-EOF-\n"; } int @@ -74,7 +74,7 @@ main(int argc, char* argv[]) ParserCallbacks cb; page.parseContents(&cb); } catch (std::exception& e) { - std::cerr << whoami << ": " << e.what() << std::endl; + std::cerr << whoami << ": " << e.what() << '\n'; exit(2); } diff --git a/examples/pdf-set-form-values.cc b/examples/pdf-set-form-values.cc index 810b9fa..5f86f84 100644 --- a/examples/pdf-set-form-values.cc +++ b/examples/pdf-set-form-values.cc @@ -11,8 +11,8 @@ static char const* whoami = nullptr; void usage() { - std::cerr << "Usage: " << whoami << " infile.pdf outfile.pdf value" << std::endl - << "Set the value of all text fields to a specified value" << std::endl; + std::cerr << "Usage: " << whoami << " infile.pdf outfile.pdf value\n" + << "Set the value of all text fields to a specified value\n"; exit(2); } @@ -68,7 +68,7 @@ main(int argc, char* argv[]) w.setStaticID(true); // for testing only w.write(); } catch (std::exception& e) { - std::cerr << whoami << " processing file " << infilename << ": " << e.what() << std::endl; + std::cerr << whoami << " processing file " << infilename << ": " << e.what() << '\n'; exit(2); } diff --git a/examples/pdf-split-pages.cc b/examples/pdf-split-pages.cc index fde4bc1..54a4521 100644 --- a/examples/pdf-split-pages.cc +++ b/examples/pdf-split-pages.cc @@ -42,7 +42,7 @@ process(char const* whoami, char const* infile, std::string outprefix) void usage(char const* whoami) { - std::cerr << "Usage: " << whoami << " infile outprefix" << std::endl; + std::cerr << "Usage: " << whoami << " infile outprefix\n"; exit(2); } @@ -64,7 +64,7 @@ main(int argc, char* argv[]) try { process(whoami, argv[1], argv[2]); } catch (std::exception const& e) { - std::cerr << whoami << ": exception: " << e.what() << std::endl; + std::cerr << whoami << ": exception: " << e.what() << '\n'; return 2; } return 0; diff --git a/examples/qpdf-job.cc b/examples/qpdf-job.cc index c2952ee..bfcc4ba 100644 --- a/examples/qpdf-job.cc +++ b/examples/qpdf-job.cc @@ -10,11 +10,10 @@ static char const* whoami = nullptr; static void usage() { - std::cerr << "Usage: " << whoami << std::endl + std::cerr << "Usage: " << whoami << '\n' << "This program linearizes the first page of in.pdf to out1.pdf, out2.pdf, and" - << std::endl - << " out3.pdf, each demonstrating a different way to use the QPDFJob API" - << std::endl; + << '\n' + << " out3.pdf, each demonstrating a different way to use the QPDFJob API" << '\n'; exit(2); } @@ -49,9 +48,9 @@ main(int argc, char* argv[]) ->compressStreams("n") // avoid dependency on zlib output ->checkConfiguration(); j.run(); - std::cout << "out1 status: " << j.getExitCode() << std::endl; + std::cout << "out1 status: " << j.getExitCode() << '\n'; } catch (std::exception& e) { - std::cerr << "exception: " << e.what() << std::endl; + std::cerr << "exception: " << e.what() << '\n'; return 2; } @@ -71,9 +70,9 @@ main(int argc, char* argv[]) QPDFJob j; j.initializeFromArgv(new_argv); j.run(); - std::cout << "out2 status: " << j.getExitCode() << std::endl; + std::cout << "out2 status: " << j.getExitCode() << '\n'; } catch (std::exception& e) { - std::cerr << "exception: " << e.what() << std::endl; + std::cerr << "exception: " << e.what() << '\n'; return 2; } @@ -95,9 +94,9 @@ main(int argc, char* argv[]) } )"); j.run(); - std::cout << "out3 status: " << j.getExitCode() << std::endl; + std::cout << "out3 status: " << j.getExitCode() << '\n'; } catch (std::exception& e) { - std::cerr << "exception: " << e.what() << std::endl; + std::cerr << "exception: " << e.what() << '\n'; return 2; } diff --git a/examples/qpdfjob-save-attachment.cc b/examples/qpdfjob-save-attachment.cc index 790d808..51d2314 100644 --- a/examples/qpdfjob-save-attachment.cc +++ b/examples/qpdfjob-save-attachment.cc @@ -13,7 +13,7 @@ main(int argc, char* argv[]) auto whoami = QUtil::getWhoami(argv[0]); if (argc != 4) { - std::cerr << "Usage: " << whoami << " file attachment-key outfile" << std::endl; + std::cerr << "Usage: " << whoami << " file attachment-key outfile" << '\n'; exit(2); } @@ -40,10 +40,10 @@ main(int argc, char* argv[]) j.initializeFromArgv(j_argv); j.run(); } catch (std::exception& e) { - std::cerr << whoami << ": " << e.what() << std::endl; + std::cerr << whoami << ": " << e.what() << '\n'; exit(2); } - std::cout << whoami << ": wrote attachment to " << outfilename << std::endl; + std::cout << whoami << ": wrote attachment to " << outfilename << '\n'; return 0; } diff --git a/fuzz/ascii85_fuzzer.cc b/fuzz/ascii85_fuzzer.cc index daf6628..3fdc94c 100644 --- a/fuzz/ascii85_fuzzer.cc +++ b/fuzz/ascii85_fuzzer.cc @@ -37,7 +37,7 @@ FuzzHelper::run() try { doChecks(); } catch (std::runtime_error const& e) { - std::cerr << "runtime_error: " << e.what() << std::endl; + std::cerr << "runtime_error: " << e.what() << '\n'; } } diff --git a/fuzz/dct_fuzzer.cc b/fuzz/dct_fuzzer.cc index a99e9e0..f51c53f 100644 --- a/fuzz/dct_fuzzer.cc +++ b/fuzz/dct_fuzzer.cc @@ -49,7 +49,7 @@ FuzzHelper::run() try { doChecks(); } catch (std::runtime_error const& e) { - std::cerr << "runtime_error: " << e.what() << std::endl; + std::cerr << "runtime_error: " << e.what() << '\n'; } } diff --git a/fuzz/flate_fuzzer.cc b/fuzz/flate_fuzzer.cc index 97e10dd..ca6fc7a 100644 --- a/fuzz/flate_fuzzer.cc +++ b/fuzz/flate_fuzzer.cc @@ -37,7 +37,7 @@ FuzzHelper::run() try { doChecks(); } catch (std::runtime_error const& e) { - std::cerr << "runtime_error: " << e.what() << std::endl; + std::cerr << "runtime_error: " << e.what() << '\n'; } } diff --git a/fuzz/hex_fuzzer.cc b/fuzz/hex_fuzzer.cc index 0ce7b2e..ea759bc 100644 --- a/fuzz/hex_fuzzer.cc +++ b/fuzz/hex_fuzzer.cc @@ -37,7 +37,7 @@ FuzzHelper::run() try { doChecks(); } catch (std::runtime_error const& e) { - std::cerr << "runtime_error: " << e.what() << std::endl; + std::cerr << "runtime_error: " << e.what() << '\n'; } } diff --git a/fuzz/json_fuzzer.cc b/fuzz/json_fuzzer.cc index 8b46a0a..272a206 100644 --- a/fuzz/json_fuzzer.cc +++ b/fuzz/json_fuzzer.cc @@ -30,7 +30,7 @@ FuzzHelper::doChecks() try { JSON::parse(std::string(reinterpret_cast(data), size)); } catch (std::runtime_error& e) { - std::cerr << "runtime_error parsing json: " << e.what() << std::endl; + std::cerr << "runtime_error parsing json: " << e.what() << '\n'; } QPDF q; q.setMaxWarnings(1000); @@ -45,7 +45,7 @@ FuzzHelper::run() try { doChecks(); } catch (std::runtime_error const& e) { - std::cerr << "runtime_error: " << e.what() << std::endl; + std::cerr << "runtime_error: " << e.what() << '\n'; } } diff --git a/fuzz/lzw_fuzzer.cc b/fuzz/lzw_fuzzer.cc index 5e01750..ab13c52 100644 --- a/fuzz/lzw_fuzzer.cc +++ b/fuzz/lzw_fuzzer.cc @@ -37,7 +37,7 @@ FuzzHelper::run() try { doChecks(); } catch (std::runtime_error const& e) { - std::cerr << "runtime_error: " << e.what() << std::endl; + std::cerr << "runtime_error: " << e.what() << '\n'; } } diff --git a/fuzz/pngpredictor_fuzzer.cc b/fuzz/pngpredictor_fuzzer.cc index 7a39c8e..b30ec6a 100644 --- a/fuzz/pngpredictor_fuzzer.cc +++ b/fuzz/pngpredictor_fuzzer.cc @@ -37,7 +37,7 @@ FuzzHelper::run() try { doChecks(); } catch (std::runtime_error const& e) { - std::cerr << "runtime_error: " << e.what() << std::endl; + std::cerr << "runtime_error: " << e.what() << '\n'; } } diff --git a/fuzz/qpdf_crypt_fuzzer.cc b/fuzz/qpdf_crypt_fuzzer.cc index f310b50..9d0128f 100644 --- a/fuzz/qpdf_crypt_fuzzer.cc +++ b/fuzz/qpdf_crypt_fuzzer.cc @@ -76,9 +76,9 @@ FuzzHelper::doWrite(std::shared_ptr w) try { w->write(); } catch (QPDFExc const& e) { - std::cerr << e.what() << std::endl; + std::cerr << e.what() << '\n'; } catch (std::runtime_error const& e) { - std::cerr << e.what() << std::endl; + std::cerr << e.what() << '\n'; } } @@ -135,9 +135,9 @@ FuzzHelper::run() try { doChecks(); } catch (QPDFExc const& e) { - std::cerr << "QPDFExc: " << e.what() << std::endl; + std::cerr << "QPDFExc: " << e.what() << '\n'; } catch (std::runtime_error const& e) { - std::cerr << "runtime_error: " << e.what() << std::endl; + std::cerr << "runtime_error: " << e.what() << '\n'; } } diff --git a/fuzz/qpdf_crypt_insecure_fuzzer.cc b/fuzz/qpdf_crypt_insecure_fuzzer.cc index 76d1337..8b6c9b3 100644 --- a/fuzz/qpdf_crypt_insecure_fuzzer.cc +++ b/fuzz/qpdf_crypt_insecure_fuzzer.cc @@ -75,9 +75,9 @@ FuzzHelper::doWrite(std::shared_ptr w) try { w->write(); } catch (QPDFExc const& e) { - std::cerr << e.what() << std::endl; + std::cerr << e.what() << '\n'; } catch (std::runtime_error const& e) { - std::cerr << e.what() << std::endl; + std::cerr << e.what() << '\n'; } } @@ -135,9 +135,9 @@ FuzzHelper::run() try { doChecks(); } catch (QPDFExc const& e) { - std::cerr << "QPDFExc: " << e.what() << std::endl; + std::cerr << "QPDFExc: " << e.what() << '\n'; } catch (std::runtime_error const& e) { - std::cerr << "runtime_error: " << e.what() << std::endl; + std::cerr << "runtime_error: " << e.what() << '\n'; } } diff --git a/fuzz/qpdf_fuzzer.cc b/fuzz/qpdf_fuzzer.cc index 65aac38..d43c756 100644 --- a/fuzz/qpdf_fuzzer.cc +++ b/fuzz/qpdf_fuzzer.cc @@ -75,9 +75,9 @@ FuzzHelper::doWrite(std::shared_ptr w) try { w->write(); } catch (QPDFExc const& e) { - std::cerr << e.what() << std::endl; + std::cerr << e.what() << '\n'; } catch (std::runtime_error const& e) { - std::cerr << e.what() << std::endl; + std::cerr << e.what() << '\n'; } } @@ -133,9 +133,9 @@ FuzzHelper::run() try { doChecks(); } catch (QPDFExc const& e) { - std::cerr << "QPDFExc: " << e.what() << std::endl; + std::cerr << "QPDFExc: " << e.what() << '\n'; } catch (std::runtime_error const& e) { - std::cerr << "runtime_error: " << e.what() << std::endl; + std::cerr << "runtime_error: " << e.what() << '\n'; } } diff --git a/fuzz/qpdf_lin_fuzzer.cc b/fuzz/qpdf_lin_fuzzer.cc index 3be6a7d..a6b9c31 100644 --- a/fuzz/qpdf_lin_fuzzer.cc +++ b/fuzz/qpdf_lin_fuzzer.cc @@ -75,9 +75,9 @@ FuzzHelper::doWrite(std::shared_ptr w) try { w->write(); } catch (QPDFExc const& e) { - std::cerr << e.what() << std::endl; + std::cerr << e.what() << '\n'; } catch (std::runtime_error const& e) { - std::cerr << e.what() << std::endl; + std::cerr << e.what() << '\n'; } } @@ -134,9 +134,9 @@ FuzzHelper::run() try { doChecks(); } catch (QPDFExc const& e) { - std::cerr << "QPDFExc: " << e.what() << std::endl; + std::cerr << "QPDFExc: " << e.what() << '\n'; } catch (std::runtime_error const& e) { - std::cerr << "runtime_error: " << e.what() << std::endl; + std::cerr << "runtime_error: " << e.what() << '\n'; } } diff --git a/fuzz/qpdf_outlines_fuzzer.cc b/fuzz/qpdf_outlines_fuzzer.cc index 7a2f791..669395b 100644 --- a/fuzz/qpdf_outlines_fuzzer.cc +++ b/fuzz/qpdf_outlines_fuzzer.cc @@ -111,9 +111,9 @@ FuzzHelper::run() try { doChecks(); } catch (QPDFExc const& e) { - std::cerr << "QPDFExc: " << e.what() << std::endl; + std::cerr << "QPDFExc: " << e.what() << '\n'; } catch (std::runtime_error const& e) { - std::cerr << "runtime_error: " << e.what() << std::endl; + std::cerr << "runtime_error: " << e.what() << '\n'; } } diff --git a/fuzz/qpdf_pages_fuzzer.cc b/fuzz/qpdf_pages_fuzzer.cc index 66c8439..4dd7ae5 100644 --- a/fuzz/qpdf_pages_fuzzer.cc +++ b/fuzz/qpdf_pages_fuzzer.cc @@ -132,9 +132,9 @@ FuzzHelper::run() try { doChecks(); } catch (QPDFExc const& e) { - std::cerr << "QPDFExc: " << e.what() << std::endl; + std::cerr << "QPDFExc: " << e.what() << '\n'; } catch (std::runtime_error const& e) { - std::cerr << "runtime_error: " << e.what() << std::endl; + std::cerr << "runtime_error: " << e.what() << '\n'; } } diff --git a/fuzz/runlength_fuzzer.cc b/fuzz/runlength_fuzzer.cc index b19cd30..c185f51 100644 --- a/fuzz/runlength_fuzzer.cc +++ b/fuzz/runlength_fuzzer.cc @@ -38,7 +38,7 @@ FuzzHelper::run() try { doChecks(); } catch (std::runtime_error const& e) { - std::cerr << "runtime_error: " << e.what() << std::endl; + std::cerr << "runtime_error: " << e.what() << '\n'; } } diff --git a/fuzz/standalone_fuzz_target_runner.cc b/fuzz/standalone_fuzz_target_runner.cc index 9d57481..5437e33 100644 --- a/fuzz/standalone_fuzz_target_runner.cc +++ b/fuzz/standalone_fuzz_target_runner.cc @@ -12,7 +12,7 @@ main(int argc, char** argv) size_t size = 0; QUtil::read_file_into_memory(argv[i], file_buf, size); LLVMFuzzerTestOneInput(reinterpret_cast(file_buf.get()), size); - std::cout << argv[i] << " successful" << std::endl; + std::cout << argv[i] << " successful" << '\n'; } return 0; } diff --git a/fuzz/tiffpredictor_fuzzer.cc b/fuzz/tiffpredictor_fuzzer.cc index 21b7f61..5811a0f 100644 --- a/fuzz/tiffpredictor_fuzzer.cc +++ b/fuzz/tiffpredictor_fuzzer.cc @@ -41,7 +41,7 @@ FuzzHelper::run() try { doChecks(); } catch (std::runtime_error const& e) { - std::cerr << "runtime_error: " << e.what() << std::endl; + std::cerr << "runtime_error: " << e.what() << '\n'; } } diff --git a/include/qpdf/ClosedFileInputSource.hh b/include/qpdf/ClosedFileInputSource.hh index b5d7e33..f93764d 100644 --- a/include/qpdf/ClosedFileInputSource.hh +++ b/include/qpdf/ClosedFileInputSource.hh @@ -69,9 +69,9 @@ class QPDF_DLL_CLASS ClosedFileInputSource: public InputSource void after(); std::string filename; - qpdf_offset_t offset; + qpdf_offset_t offset{0}; std::shared_ptr fis; - bool stay_open; + bool stay_open{false}; }; #endif // QPDF_CLOSEDFILEINPUTSOURCE_HH diff --git a/include/qpdf/QPDFAcroFormDocumentHelper.hh b/include/qpdf/QPDFAcroFormDocumentHelper.hh index 248525a..db75226 100644 --- a/include/qpdf/QPDFAcroFormDocumentHelper.hh +++ b/include/qpdf/QPDFAcroFormDocumentHelper.hh @@ -234,10 +234,10 @@ class QPDFAcroFormDocumentHelper: public QPDFDocumentHelper ~Members() = default; private: - Members(); + Members() = default; Members(Members const&) = delete; - bool cache_valid; + bool cache_valid{false}; std::map> field_to_annotations; std::map annotation_to_field; std::map field_to_name; diff --git a/include/qpdf/QPDFJob.hh b/include/qpdf/QPDFJob.hh index 0874ac7..f6719a9 100644 --- a/include/qpdf/QPDFJob.hh +++ b/include/qpdf/QPDFJob.hh @@ -158,10 +158,11 @@ class QPDFJob struct PageSpec { - PageSpec(std::string const& filename, char const* password, std::string const& range); + PageSpec( + std::string const& filename, std::string const& password, std::string const& range); std::string filename; - std::shared_ptr password; + std::string password; std::string range; }; @@ -450,7 +451,7 @@ class QPDFJob std::string which; std::string filename; - std::shared_ptr password; + std::string password; std::string to_nr; std::string from_nr; std::string repeat_nr; @@ -591,7 +592,7 @@ class QPDFJob bool warnings{false}; unsigned long encryption_status{0}; bool verbose{false}; - std::shared_ptr password; + std::string password; bool linearize{false}; bool decrypt{false}; bool remove_restrictions{false}; @@ -602,7 +603,7 @@ class QPDFJob bool warnings_exit_zero{false}; bool copy_encryption{false}; std::string encryption_file; - std::shared_ptr encryption_file_password; + std::string encryption_file_password; bool encrypt{false}; bool password_is_hex_key{false}; bool suppress_password_recovery{false}; @@ -711,8 +712,9 @@ class QPDFJob bool replace_input{false}; bool check_is_encrypted{false}; bool check_requires_password{false}; - std::shared_ptr infilename; - std::shared_ptr outfilename; + std::string infilename; + bool empty_input{false}; + std::string outfilename; bool json_input{false}; bool json_output{false}; std::string update_from_json; diff --git a/include/qpdf/QPDFObjGen.hh b/include/qpdf/QPDFObjGen.hh index 8bdeea7..f984668 100644 --- a/include/qpdf/QPDFObjGen.hh +++ b/include/qpdf/QPDFObjGen.hh @@ -110,7 +110,7 @@ class QPDFObjGen add(QPDFObjGen og) { if (og.isIndirect()) { - if (count(og) > 0) { + if (count(og)) { return false; } emplace(og); diff --git a/libqpdf/AES_PDF_native.cc b/libqpdf/AES_PDF_native.cc index 42f1cda..8808d20 100644 --- a/libqpdf/AES_PDF_native.cc +++ b/libqpdf/AES_PDF_native.cc @@ -17,8 +17,7 @@ AES_PDF_native::AES_PDF_native( unsigned char* cbc_block) : encrypt(encrypt), cbc_mode(cbc_mode), - cbc_block(cbc_block), - nrounds(0) + cbc_block(cbc_block) { size_t keybits = 8 * key_bytes; this->key = std::make_unique(key_bytes); diff --git a/libqpdf/BitWriter.cc b/libqpdf/BitWriter.cc index 2558592..c77eece 100644 --- a/libqpdf/BitWriter.cc +++ b/libqpdf/BitWriter.cc @@ -5,9 +5,7 @@ #include BitWriter::BitWriter(Pipeline* pl) : - pl(pl), - ch(0), - bit_offset(7) + pl(pl) { } diff --git a/libqpdf/ClosedFileInputSource.cc b/libqpdf/ClosedFileInputSource.cc index 2a6cb89..5995906 100644 --- a/libqpdf/ClosedFileInputSource.cc +++ b/libqpdf/ClosedFileInputSource.cc @@ -3,9 +3,7 @@ #include ClosedFileInputSource::ClosedFileInputSource(char const* filename) : - filename(filename), - offset(0), - stay_open(false) + filename(filename) { } diff --git a/libqpdf/ContentNormalizer.cc b/libqpdf/ContentNormalizer.cc index 6ec6cf9..03496d4 100644 --- a/libqpdf/ContentNormalizer.cc +++ b/libqpdf/ContentNormalizer.cc @@ -5,12 +5,6 @@ using namespace qpdf; -ContentNormalizer::ContentNormalizer() : - any_bad_tokens(false), - last_token_was_bad(false) -{ -} - void ContentNormalizer::handleToken(QPDFTokenizer::Token const& token) { diff --git a/libqpdf/InsecureRandomDataProvider.cc b/libqpdf/InsecureRandomDataProvider.cc index 1c7fb9e..5c317e7 100644 --- a/libqpdf/InsecureRandomDataProvider.cc +++ b/libqpdf/InsecureRandomDataProvider.cc @@ -4,11 +4,6 @@ #include #include -InsecureRandomDataProvider::InsecureRandomDataProvider() : - seeded_random(false) -{ -} - void InsecureRandomDataProvider::provideRandomData(unsigned char* data, size_t len) { diff --git a/libqpdf/JSON.cc b/libqpdf/JSON.cc index 80bd6c6..852e53c 100644 --- a/libqpdf/JSON.cc +++ b/libqpdf/JSON.cc @@ -490,24 +490,18 @@ JSON::checkSchemaInternal( } } - if (sch_dict && (!pattern_key.empty())) { + if (sch_dict && !pattern_key.empty()) { auto pattern_schema = sch_dict->members[pattern_key].m->value.get(); - for (auto const& iter: this_dict->members) { - std::string const& key = iter.first; + for (auto const& [key, val]: this_dict->members) { checkSchemaInternal( - this_dict->members[key].m->value.get(), - pattern_schema, - flags, - errors, - prefix + "." + key); + val.m->value.get(), pattern_schema, flags, errors, prefix + "." + key); } } else if (sch_dict) { - for (auto& iter: sch_dict->members) { - std::string const& key = iter.first; - if (this_dict->members.count(key)) { + for (auto& [key, val]: sch_dict->members) { + if (this_dict->members.contains(key)) { checkSchemaInternal( this_dict->members[key].m->value.get(), - iter.second.m->value.get(), + val.m->value.get(), flags, errors, prefix + "." + key); @@ -516,18 +510,17 @@ JSON::checkSchemaInternal( QTC::TC("libtests", "JSON optional key"); } else { QTC::TC("libtests", "JSON key missing in object"); - errors.push_back( + errors.emplace_back( err_prefix + ": key \"" + key + "\" is present in schema but missing in object"); } } } - for (auto const& iter: this_dict->members) { - std::string const& key = iter.first; - if (sch_dict->members.count(key) == 0) { + for (auto const& item: this_dict->members) { + if (!sch_dict->members.contains(item.first)) { QTC::TC("libtests", "JSON key extra in object"); - errors.push_back( - err_prefix + ": key \"" + key + + errors.emplace_back( + err_prefix + ": key \"" + item.first + "\" is not present in schema but appears in object"); } } @@ -554,9 +547,9 @@ JSON::checkSchemaInternal( checkSchemaInternal( this_v, sch_arr->elements.at(0).m->value.get(), flags, errors, prefix); } - } else if (!this_arr || (this_arr->elements.size() != n_elements)) { + } else if (!this_arr || this_arr->elements.size() != n_elements) { QTC::TC("libtests", "JSON schema array length mismatch"); - errors.push_back( + errors.emplace_back( err_prefix + " is supposed to be an array of length " + std::to_string(n_elements)); return false; } else { @@ -576,7 +569,7 @@ JSON::checkSchemaInternal( } } else if (!sch_str) { QTC::TC("libtests", "JSON schema other type"); - errors.push_back(err_prefix + " schema value is not dictionary, array, or string"); + errors.emplace_back(err_prefix + " schema value is not dictionary, array, or string"); return false; } diff --git a/libqpdf/NNTree.cc b/libqpdf/NNTree.cc index fd7d437..210b8db 100644 --- a/libqpdf/NNTree.cc +++ b/libqpdf/NNTree.cc @@ -28,8 +28,7 @@ error(QPDF& qpdf, QPDFObjectHandle& node, std::string const& msg) } NNTreeIterator::NNTreeIterator(NNTreeImpl& impl) : - impl(impl), - item_number(-1) + impl(impl) { } @@ -666,7 +665,6 @@ NNTreeImpl::NNTreeImpl( NNTreeDetails const& details, QPDF& qpdf, QPDFObjectHandle& oh, bool auto_repair) : details(details), qpdf(qpdf), - split_threshold(32), oh(oh), auto_repair(auto_repair) { diff --git a/libqpdf/Pl_Flate.cc b/libqpdf/Pl_Flate.cc index a28a1a3..9a575ad 100644 --- a/libqpdf/Pl_Flate.cc +++ b/libqpdf/Pl_Flate.cc @@ -29,7 +29,7 @@ Pl_Flate::Members::Members(size_t out_bufsize, action_e action) : // Indirect through zdata to reach the z_stream so we don't have to include zlib.h in // Pl_Flate.hh. This means people using shared library versions of qpdf don't have to have zlib // development files available, which particularly helps in a Windows environment. - this->zdata = new z_stream; + zdata = new z_stream; if (out_bufsize > UINT_MAX) { throw std::runtime_error( @@ -52,8 +52,8 @@ Pl_Flate::Members::Members(size_t out_bufsize, action_e action) : Pl_Flate::Members::~Members() { - if (this->initialized) { - z_stream& zstream = *(static_cast(this->zdata)); + if (initialized) { + z_stream& zstream = *(static_cast(zdata)); if (action == a_deflate) { deflateEnd(&zstream); } else { @@ -62,7 +62,7 @@ Pl_Flate::Members::~Members() } delete static_cast(this->zdata); - this->zdata = nullptr; + zdata = nullptr; } Pl_Flate::Pl_Flate( @@ -99,7 +99,7 @@ Pl_Flate::setWarnCallback(std::function callback) void Pl_Flate::warn(char const* msg, int code) { - if (m->callback != nullptr) { + if (m->callback) { m->callback(msg, code); } } @@ -107,7 +107,7 @@ Pl_Flate::warn(char const* msg, int code) void Pl_Flate::write(unsigned char const* data, size_t len) { - if (m->outbuf == nullptr) { + if (!m->outbuf) { throw std::logic_error( this->identifier + ": Pl_Flate: write() called after finish() called"); } @@ -184,7 +184,7 @@ Pl_Flate::handleData(unsigned char const* data, size_t len, int flush) // this error (including at least one in qpdf's test suite). In some cases, we want to // know about this, because it indicates incorrect compression, so call a callback if // provided. - this->warn("input stream is complete but output may still be valid", err); + warn("input stream is complete but output may still be valid", err); done = true; break; @@ -215,7 +215,7 @@ Pl_Flate::handleData(unsigned char const* data, size_t len, int flush) break; default: - this->checkError("data", err); + checkError("data", err); break; } } @@ -271,7 +271,7 @@ Pl_Flate::checkError(char const* prefix, int error_code) z_stream& zstream = *(static_cast(m->zdata)); if (error_code != Z_OK) { char const* action_str = (m->action == a_deflate ? "deflate" : "inflate"); - std::string msg = this->identifier + ": " + action_str + ": " + prefix + ": "; + std::string msg = identifier + ": " + action_str + ": " + prefix + ": "; if (zstream.msg) { msg += zstream.msg; diff --git a/libqpdf/Pl_PNGFilter.cc b/libqpdf/Pl_PNGFilter.cc index e3930e2..e3a3528 100644 --- a/libqpdf/Pl_PNGFilter.cc +++ b/libqpdf/Pl_PNGFilter.cc @@ -39,7 +39,7 @@ Pl_PNGFilter::Pl_PNGFilter( throw std::runtime_error( "PNGFilter created with invalid bits_per_sample not 1, 2, 4, 8, or 16"); } - this->bytes_per_pixel = ((bits_per_sample * samples_per_pixel) + 7) / 8; + bytes_per_pixel = ((bits_per_sample * samples_per_pixel) + 7) / 8; unsigned long long bpr = ((columns * bits_per_sample * samples_per_pixel) + 7) / 8; if ((bpr == 0) || (bpr > (UINT_MAX - 1))) { throw std::runtime_error("PNGFilter created with invalid columns value"); @@ -47,16 +47,16 @@ Pl_PNGFilter::Pl_PNGFilter( if (memory_limit > 0 && bpr > (memory_limit / 2U)) { throw std::runtime_error("PNGFilter memory limit exceeded"); } - this->bytes_per_row = bpr & UINT_MAX; - this->buf1 = QUtil::make_shared_array(this->bytes_per_row + 1); - this->buf2 = QUtil::make_shared_array(this->bytes_per_row + 1); - memset(this->buf1.get(), 0, this->bytes_per_row + 1); - memset(this->buf2.get(), 0, this->bytes_per_row + 1); - this->cur_row = this->buf1.get(); - this->prev_row = this->buf2.get(); + bytes_per_row = bpr & UINT_MAX; + buf1 = QUtil::make_shared_array(bytes_per_row + 1); + buf2 = QUtil::make_shared_array(bytes_per_row + 1); + memset(buf1.get(), 0, bytes_per_row + 1); + memset(buf2.get(), 0, bytes_per_row + 1); + cur_row = buf1.get(); + prev_row = buf2.get(); // number of bytes per incoming row - this->incoming = (action == a_encode ? this->bytes_per_row : this->bytes_per_row + 1); + incoming = (action == a_encode ? bytes_per_row : bytes_per_row + 1); } void @@ -68,34 +68,34 @@ Pl_PNGFilter::setMemoryLimit(unsigned long long limit) void Pl_PNGFilter::write(unsigned char const* data, size_t len) { - size_t left = this->incoming - this->pos; + size_t left = incoming - pos; size_t offset = 0; while (len >= left) { // finish off current row - memcpy(this->cur_row + this->pos, data + offset, left); + memcpy(cur_row + pos, data + offset, left); offset += left; len -= left; processRow(); // Swap rows - unsigned char* t = this->prev_row; - this->prev_row = this->cur_row; - this->cur_row = t ? t : this->buf2.get(); - memset(this->cur_row, 0, this->bytes_per_row + 1); - left = this->incoming; - this->pos = 0; + unsigned char* t = prev_row; + prev_row = cur_row; + cur_row = t ? t : buf2.get(); + memset(cur_row, 0, bytes_per_row + 1); + left = incoming; + pos = 0; } if (len) { - memcpy(this->cur_row + this->pos, data + offset, len); + memcpy(cur_row + pos, data + offset, len); } - this->pos += len; + pos += len; } void Pl_PNGFilter::processRow() { - if (this->action == a_encode) { + if (action == a_encode) { encodeRow(); } else { decodeRow(); @@ -105,22 +105,22 @@ Pl_PNGFilter::processRow() void Pl_PNGFilter::decodeRow() { - int filter = this->cur_row[0]; - if (this->prev_row) { + int filter = cur_row[0]; + if (prev_row) { switch (filter) { case 0: break; case 1: - this->decodeSub(); + decodeSub(); break; case 2: - this->decodeUp(); + decodeUp(); break; case 3: - this->decodeAverage(); + decodeAverage(); break; case 4: - this->decodePaeth(); + decodePaeth(); break; default: // ignore @@ -128,17 +128,17 @@ Pl_PNGFilter::decodeRow() } } - next()->write(this->cur_row + 1, this->bytes_per_row); + next()->write(cur_row + 1, bytes_per_row); } void Pl_PNGFilter::decodeSub() { QTC::TC("libtests", "Pl_PNGFilter decodeSub"); - unsigned char* buffer = this->cur_row + 1; - unsigned int bpp = this->bytes_per_pixel; + unsigned char* buffer = cur_row + 1; + unsigned int bpp = bytes_per_pixel; - for (unsigned int i = 0; i < this->bytes_per_row; ++i) { + for (unsigned int i = 0; i < bytes_per_row; ++i) { unsigned char left = 0; if (i >= bpp) { @@ -153,10 +153,10 @@ void Pl_PNGFilter::decodeUp() { QTC::TC("libtests", "Pl_PNGFilter decodeUp"); - unsigned char* buffer = this->cur_row + 1; - unsigned char* above_buffer = this->prev_row + 1; + unsigned char* buffer = cur_row + 1; + unsigned char* above_buffer = prev_row + 1; - for (unsigned int i = 0; i < this->bytes_per_row; ++i) { + for (unsigned int i = 0; i < bytes_per_row; ++i) { unsigned char up = above_buffer[i]; buffer[i] = static_cast(buffer[i] + up); } @@ -166,11 +166,11 @@ void Pl_PNGFilter::decodeAverage() { QTC::TC("libtests", "Pl_PNGFilter decodeAverage"); - unsigned char* buffer = this->cur_row + 1; - unsigned char* above_buffer = this->prev_row + 1; - unsigned int bpp = this->bytes_per_pixel; + unsigned char* buffer = cur_row + 1; + unsigned char* above_buffer = prev_row + 1; + unsigned int bpp = bytes_per_pixel; - for (unsigned int i = 0; i < this->bytes_per_row; ++i) { + for (unsigned int i = 0; i < bytes_per_row; ++i) { int left = 0; int up = 0; @@ -187,11 +187,11 @@ void Pl_PNGFilter::decodePaeth() { QTC::TC("libtests", "Pl_PNGFilter decodePaeth"); - unsigned char* buffer = this->cur_row + 1; - unsigned char* above_buffer = this->prev_row + 1; - unsigned int bpp = this->bytes_per_pixel; + unsigned char* buffer = cur_row + 1; + unsigned char* above_buffer = prev_row + 1; + unsigned int bpp = bytes_per_pixel; - for (unsigned int i = 0; i < this->bytes_per_row; ++i) { + for (unsigned int i = 0; i < bytes_per_row; ++i) { int left = 0; int up = above_buffer[i]; int upper_left = 0; @@ -201,8 +201,7 @@ Pl_PNGFilter::decodePaeth() upper_left = above_buffer[i - bpp]; } - buffer[i] = - static_cast(buffer[i] + this->PaethPredictor(left, up, upper_left)); + buffer[i] = static_cast(buffer[i] + PaethPredictor(left, up, upper_left)); } } @@ -229,27 +228,27 @@ Pl_PNGFilter::encodeRow() // For now, hard-code to using UP filter. unsigned char ch = 2; next()->write(&ch, 1); - if (this->prev_row) { - for (unsigned int i = 0; i < this->bytes_per_row; ++i) { - ch = static_cast(this->cur_row[i] - this->prev_row[i]); + if (prev_row) { + for (unsigned int i = 0; i < bytes_per_row; ++i) { + ch = static_cast(cur_row[i] - prev_row[i]); next()->write(&ch, 1); } } else { - next()->write(this->cur_row, this->bytes_per_row); + next()->write(cur_row, bytes_per_row); } } void Pl_PNGFilter::finish() { - if (this->pos) { + if (pos) { // write partial row processRow(); } - this->prev_row = nullptr; - this->cur_row = buf1.get(); - this->pos = 0; - memset(this->cur_row, 0, this->bytes_per_row + 1); + prev_row = nullptr; + cur_row = buf1.get(); + pos = 0; + memset(cur_row, 0, bytes_per_row + 1); next()->finish(); } diff --git a/libqpdf/Pl_SHA2.cc b/libqpdf/Pl_SHA2.cc index 090d778..9514d1c 100644 --- a/libqpdf/Pl_SHA2.cc +++ b/libqpdf/Pl_SHA2.cc @@ -5,8 +5,7 @@ #include Pl_SHA2::Pl_SHA2(int bits, Pipeline* next) : - Pipeline("sha2", next), - in_progress(false) + Pipeline("sha2", next) { if (bits) { resetBits(bits); diff --git a/libqpdf/QPDF.cc b/libqpdf/QPDF.cc index c048f75..a0c2054 100644 --- a/libqpdf/QPDF.cc +++ b/libqpdf/QPDF.cc @@ -564,7 +564,7 @@ QPDF::copyForeignObject(QPDFObjectHandle foreign) obj_copier.to_copy.clear(); auto og = foreign.getObjGen(); - if (!obj_copier.object_map.count(og)) { + if (!obj_copier.object_map.contains(og)) { warn(damagedPDF( other.getFilename() + " object " + og.unparse(' '), foreign.getParsedOffset(), @@ -594,7 +594,7 @@ QPDF::reserveObjects(QPDFObjectHandle foreign, ObjCopier& obj_copier, bool top) QTC::TC("qpdf", "QPDF loop reserving objects"); return; } - if (obj_copier.object_map.count(foreign_og) > 0) { + if (obj_copier.object_map.contains(foreign_og)) { QTC::TC("qpdf", "QPDF already reserved object"); if (!(top && foreign.isPageObject() && obj_copier.object_map[foreign_og].isNull())) { obj_copier.visiting.erase(foreign); diff --git a/libqpdf/QPDFAcroFormDocumentHelper.cc b/libqpdf/QPDFAcroFormDocumentHelper.cc index 8f47616..aa54d81 100644 --- a/libqpdf/QPDFAcroFormDocumentHelper.cc +++ b/libqpdf/QPDFAcroFormDocumentHelper.cc @@ -9,11 +9,6 @@ using namespace qpdf; -QPDFAcroFormDocumentHelper::Members::Members() : - cache_valid(false) -{ -} - QPDFAcroFormDocumentHelper::QPDFAcroFormDocumentHelper(QPDF& qpdf) : QPDFDocumentHelper(qpdf), m(new Members()) @@ -85,7 +80,7 @@ QPDFAcroFormDocumentHelper::addAndRenameFormFields(std::vector // this field's /T is always at the end of the fully qualified name, appending to /T // has the effect of appending the same thing to the fully qualified name. std::string old_name = QPDFFormFieldObjectHelper(obj).getFullyQualifiedName(); - if (renames.count(old_name) == 0) { + if (!renames.contains(old_name)) { std::string new_name = old_name; int suffix = 0; std::string append; @@ -145,7 +140,7 @@ QPDFAcroFormDocumentHelper::removeFormFields(std::set const& to_remo int i = 0; while (i < fields.getArrayNItems()) { auto field = fields.getArrayItem(i); - if (to_remove.count(field.getObjGen())) { + if (to_remove.contains(field.getObjGen())) { fields.eraseItem(i); } else { ++i; @@ -191,7 +186,7 @@ QPDFAcroFormDocumentHelper::getAnnotationsForField(QPDFFormFieldObjectHelper h) analyze(); std::vector result; QPDFObjGen og(h.getObjectHandle().getObjGen()); - if (m->field_to_annotations.count(og)) { + if (m->field_to_annotations.contains(og)) { result = m->field_to_annotations[og]; } return result; @@ -228,7 +223,7 @@ QPDFAcroFormDocumentHelper::getFieldForAnnotation(QPDFAnnotationObjectHelper h) } analyze(); QPDFObjGen og(oh.getObjGen()); - if (m->annotation_to_field.count(og)) { + if (m->annotation_to_field.contains(og)) { result = m->annotation_to_field[og]; } return result; @@ -271,7 +266,7 @@ QPDFAcroFormDocumentHelper::analyze() for (auto const& iter: getWidgetAnnotationsForPage(ph)) { QPDFObjectHandle annot(iter.getObjectHandle()); QPDFObjGen og(annot.getObjGen()); - if (m->annotation_to_field.count(og) == 0) { + if (!m->annotation_to_field.contains(og)) { QTC::TC("qpdf", "QPDFAcroFormDocumentHelper orphaned widget"); // This is not supposed to happen, but it's easy enough for us to handle this case. // Treat the annotation as its own field. This could allow qpdf to sensibly handle a @@ -542,7 +537,7 @@ ResourceReplacer::handleToken(QPDFTokenizer::Token const& token) bool wrote = false; if (token.getType() == QPDFTokenizer::tt_name) { std::string name = QPDFObjectHandle::newName(token.getValue()).getName(); - if (to_replace.count(name) && to_replace[name].count(offset)) { + if (to_replace.contains(name) && to_replace[name].contains(offset)) { QTC::TC("qpdf", "QPDFAcroFormDocumentHelper replaced DA token"); write(to_replace[name][offset]); wrote = true; @@ -675,7 +670,7 @@ QPDFAcroFormDocumentHelper::adjustAppearanceStream( resources.mergeResources(merge_with, &dr_map); // Remove empty subdictionaries for (auto iter: resources.ditems()) { - if (iter.second.isDictionary() && (iter.second.getKeys().size() == 0)) { + if (iter.second.isDictionary() && iter.second.getKeys().empty()) { resources.removeKey(iter.first); } } @@ -807,7 +802,7 @@ QPDFAcroFormDocumentHelper::transformAnnotations( std::map orig_to_copy; auto maybe_copy_object = [&](QPDFObjectHandle& to_copy) { auto og = to_copy.getObjGen(); - if (orig_to_copy.count(og)) { + if (orig_to_copy.contains(og)) { to_copy = orig_to_copy[og]; return false; } else { @@ -893,7 +888,7 @@ QPDFAcroFormDocumentHelper::transformAnnotations( auto parent = obj.getKey("/Parent"); if (parent.isIndirect()) { auto parent_og = parent.getObjGen(); - if (orig_to_copy.count(parent_og)) { + if (orig_to_copy.contains(parent_og)) { obj.replaceKey("/Parent", orig_to_copy[parent_og]); } else { parent.warnIfPossible( diff --git a/libqpdf/QPDFArgParser.cc b/libqpdf/QPDFArgParser.cc index c16c18b..18cb501 100644 --- a/libqpdf/QPDFArgParser.cc +++ b/libqpdf/QPDFArgParser.cc @@ -18,12 +18,7 @@ QPDFArgParser::Members::Members(int argc, char const* const argv[], char const* argc(argc), argv(argv), - progname_env(progname_env), - cur_arg(0), - bash_completion(false), - zsh_completion(false), - option_table(nullptr), - final_check_handler(nullptr) + progname_env(progname_env) { auto tmp = QUtil::make_unique_cstr(argv[0]); whoami = QUtil::getWhoami(tmp.get()); @@ -71,7 +66,7 @@ QPDFArgParser::selectOptionTable(std::string const& name) void QPDFArgParser::registerOptionTable(std::string const& name, bare_arg_handler_t end_handler) { - if (0 != m->option_tables.count(name)) { + if (m->option_tables.contains(name)) { QTC::TC("libtests", "QPDFArgParser register registered table"); throw std::logic_error( "QPDFArgParser: registering already registered option table " + name); @@ -84,7 +79,7 @@ QPDFArgParser::registerOptionTable(std::string const& name, bare_arg_handler_t e QPDFArgParser::OptionEntry& QPDFArgParser::registerArg(std::string const& arg) { - if (0 != m->option_table->count(arg)) { + if (m->option_table->contains(arg)) { QTC::TC("libtests", "QPDFArgParser duplicate handler"); throw std::logic_error( "QPDFArgParser: adding a duplicate handler for option " + arg + " in " + @@ -198,13 +193,13 @@ QPDFArgParser::completionCommon(bool zsh) if (!zsh) { std::cout << " -o nospace"; } - std::cout << " -C \"" << progname << "\" " << m->whoami << std::endl; + std::cout << " -C \"" << progname << "\" " << m->whoami << '\n'; // Put output before error so calling from zsh works properly std::string path = progname; size_t slash = path.find('/'); if ((slash != 0) && (slash != std::string::npos)) { std::cerr << "WARNING: " << m->whoami << " completion enabled" - << " using relative path to executable" << std::endl; + << " using relative path to executable" << '\n'; } } @@ -239,7 +234,7 @@ QPDFArgParser::handleArgFileArguments() // Support reading arguments from files. Create a new argv. Ensure that argv itself as well as // all its contents are automatically deleted by using shared pointers back to the pointers in // argv. - m->new_argv.push_back(QUtil::make_shared_cstr(m->argv[0])); + m->new_argv.emplace_back(m->argv[0]); for (int i = 1; i < m->argc; ++i) { char const* argfile = nullptr; if ((strlen(m->argv[i]) > 1) && (m->argv[i][0] == '@')) { @@ -254,16 +249,16 @@ QPDFArgParser::handleArgFileArguments() if (argfile) { readArgsFromFile(1 + m->argv[i]); } else { - m->new_argv.push_back(QUtil::make_shared_cstr(m->argv[i])); + m->new_argv.emplace_back(m->argv[i]); } } - m->argv_ph = QUtil::make_shared_array(1 + m->new_argv.size()); - for (size_t i = 0; i < m->new_argv.size(); ++i) { - m->argv_ph.get()[i] = m->new_argv.at(i).get(); + m->argv_ph.reserve(1 + m->new_argv.size()); + for (auto const& a: m->new_argv) { + m->argv_ph.push_back(a.data()); } m->argc = QIntC::to_int(m->new_argv.size()); - m->argv_ph.get()[m->argc] = nullptr; - m->argv = m->argv_ph.get(); + m->argv_ph.push_back(nullptr); + m->argv = m->argv_ph.data(); } void @@ -290,7 +285,7 @@ QPDFArgParser::handleBashArguments() case st_top: if (util::is_space(ch)) { if (!arg.empty()) { - m->bash_argv.push_back(QUtil::make_shared_cstr(arg)); + m->bash_argv.emplace_back(arg); arg.clear(); } } else if (ch == '"') { @@ -326,16 +321,16 @@ QPDFArgParser::handleBashArguments() if (m->bash_argv.empty()) { // This can't happen if properly invoked by bash, but ensure we have a valid argv[0] // regardless. - m->bash_argv.push_back(QUtil::make_shared_cstr(m->argv[0])); + m->bash_argv.emplace_back(m->argv[0]); } // Explicitly discard any non-space-terminated word. The "current word" is handled specially. - m->bash_argv_ph = QUtil::make_shared_array(1 + m->bash_argv.size()); - for (size_t i = 0; i < m->bash_argv.size(); ++i) { - m->bash_argv_ph.get()[i] = m->bash_argv.at(i).get(); + m->bash_argv_ph.reserve(1 + m->bash_argv.size()); + for (auto const& a: m->bash_argv) { + m->bash_argv_ph.push_back(a.data()); } m->argc = QIntC::to_int(m->bash_argv.size()); - m->bash_argv_ph.get()[m->argc] = nullptr; - m->argv = m->bash_argv_ph.get(); + m->bash_argv_ph.push_back(nullptr); + m->argv = m->bash_argv_ph.data(); } void @@ -360,7 +355,7 @@ QPDFArgParser::readArgsFromFile(std::string const& filename) lines = QUtil::read_lines_from_file(filename.c_str()); } for (auto const& line: lines) { - m->new_argv.push_back(QUtil::make_shared_cstr(line)); + m->new_argv.emplace_back(line); } } @@ -471,7 +466,7 @@ QPDFArgParser::parseArgs() // positional arguments. Besides, it doesn't make sense to have an empty option. arg_s = arg; size_t equal_pos = std::string::npos; - if (arg_s.length() > 0) { + if (!arg_s.empty()) { equal_pos = arg_s.find('=', 1); } if (equal_pos != std::string::npos) { @@ -481,7 +476,7 @@ QPDFArgParser::parseArgs() } if ((!m->bash_completion) && (m->argc == 2) && (m->cur_arg == 1) && - m->help_option_table.count(arg_s)) { + m->help_option_table.contains(arg_s)) { // Handle help option, which is only valid as the sole option. QTC::TC("libtests", "QPDFArgParser help option"); oep = m->help_option_table.find(arg_s); @@ -508,8 +503,8 @@ QPDFArgParser::parseArgs() } OptionEntry& oe = oep->second; - if ((oe.parameter_needed && (!have_parameter)) || - ((!oe.choices.empty() && have_parameter && (0 == oe.choices.count(parameter))))) { + if ((oe.parameter_needed && !have_parameter) || + (!oe.choices.empty() && have_parameter && !oe.choices.contains(parameter))) { std::string message = "--" + arg_s + " must be given as --" + arg_s + "="; if (oe.invalid_choice_handler) { oe.invalid_choice_handler(parameter); @@ -584,7 +579,7 @@ void QPDFArgParser::addChoicesToCompletions( option_table_t& option_table, std::string const& option, std::string const& extra_prefix) { - if (option_table.count(option) != 0) { + if (option_table.contains(option)) { OptionEntry& oe = option_table[option]; for (auto const& choice: oe.choices) { QTC::TC("libtests", "QPDFArgParser complete choices"); @@ -666,7 +661,7 @@ QPDFArgParser::handleCompletion() std::string prefix = extra_prefix + m->bash_cur; for (auto const& iter: m->completions) { if (prefix.empty() || (iter.substr(0, prefix.length()) == prefix)) { - std::cout << iter << std::endl; + std::cout << iter << '\n'; } } exit(0); @@ -686,11 +681,11 @@ QPDFArgParser::addHelpTopic( QTC::TC("libtests", "QPDFArgParser add reserved help topic"); throw std::logic_error("QPDFArgParser: can't register reserved help topic " + topic); } - if (!((topic.length() > 0) && (topic.at(0) != '-'))) { + if (topic.empty() || topic.at(0) == '-') { QTC::TC("libtests", "QPDFArgParser bad topic for help"); throw std::logic_error("QPDFArgParser: help topics must not start with -"); } - if (m->help_topics.count(topic)) { + if (m->help_topics.contains(topic)) { QTC::TC("libtests", "QPDFArgParser add existing topic"); throw std::logic_error("QPDFArgParser: topic " + topic + " has already been added"); } @@ -710,7 +705,7 @@ QPDFArgParser::addOptionHelp( QTC::TC("libtests", "QPDFArgParser bad option for help"); throw std::logic_error("QPDFArgParser: options for help must start with --"); } - if (m->option_help.count(option_name)) { + if (m->option_help.contains(option_name)) { QTC::TC("libtests", "QPDFArgParser duplicate option help"); throw std::logic_error("QPDFArgParser: option " + option_name + " already has help"); } @@ -729,13 +724,13 @@ QPDFArgParser::addOptionHelp( void QPDFArgParser::getTopHelp(std::ostringstream& msg) { - msg << "Run \"" << m->whoami << " --help=topic\" for help on a topic." << std::endl - << "Run \"" << m->whoami << " --help=--option\" for help on an option." << std::endl - << "Run \"" << m->whoami << " --help=all\" to see all available help." << std::endl - << std::endl - << "Topics:" << std::endl; + msg << "Run \"" << m->whoami << " --help=topic\" for help on a topic." << '\n' + << "Run \"" << m->whoami << " --help=--option\" for help on an option." << '\n' + << "Run \"" << m->whoami << " --help=all\" to see all available help." << '\n' + << '\n' + << "Topics:" << '\n'; for (auto const& i: m->help_topics) { - msg << " " << i.first << ": " << i.second.short_text << std::endl; + msg << " " << i.first << ": " << i.second.short_text << '\n'; } } @@ -746,29 +741,27 @@ QPDFArgParser::getAllHelp(std::ostringstream& msg) auto show = [this, &msg](std::map& topics) { for (auto const& i: topics) { auto const& topic = i.first; - msg << std::endl - << "== " << topic << " (" << i.second.short_text << ") ==" << std::endl - << std::endl; + msg << '\n' << "== " << topic << " (" << i.second.short_text << ") ==" << '\n' << '\n'; getTopicHelp(topic, i.second, msg); } }; show(m->help_topics); show(m->option_help); - msg << std::endl << "====" << std::endl; + msg << '\n' << "====" << '\n'; } void QPDFArgParser::getTopicHelp(std::string const& name, HelpTopic const& ht, std::ostringstream& msg) { if (ht.long_text.empty()) { - msg << ht.short_text << std::endl; + msg << ht.short_text << '\n'; } else { msg << ht.long_text; } if (!ht.options.empty()) { - msg << std::endl << "Related options:" << std::endl; + msg << '\n' << "Related options:" << '\n'; for (auto const& i: ht.options) { - msg << " " << i << ": " << m->option_help[i].short_text << std::endl; + msg << " " << i << ": " << m->option_help[i].short_text << '\n'; } } } @@ -782,9 +775,9 @@ QPDFArgParser::getHelp(std::string const& arg) } else { if (arg == "all") { getAllHelp(msg); - } else if (m->option_help.count(arg)) { + } else if (m->option_help.contains(arg)) { getTopicHelp(arg, m->option_help[arg], msg); - } else if (m->help_topics.count(arg)) { + } else if (m->help_topics.contains(arg)) { getTopicHelp(arg, m->help_topics[arg], msg); } else { // should not be possible diff --git a/libqpdf/QPDFCryptoProvider.cc b/libqpdf/QPDFCryptoProvider.cc index 89b5284..df5eff0 100644 --- a/libqpdf/QPDFCryptoProvider.cc +++ b/libqpdf/QPDFCryptoProvider.cc @@ -88,7 +88,7 @@ QPDFCryptoProvider::registerImpl_internal(std::string const& name, provider_fn f void QPDFCryptoProvider::setDefaultProvider_internal(std::string const& name) { - if (!m->providers.count(name)) { + if (!m->providers.contains(name)) { throw std::logic_error( "QPDFCryptoProvider: request to set default provider to unknown implementation \"" + name + "\""); diff --git a/libqpdf/QPDFJob.cc b/libqpdf/QPDFJob.cc index a78f63a..f053c83 100644 --- a/libqpdf/QPDFJob.cc +++ b/libqpdf/QPDFJob.cc @@ -262,13 +262,11 @@ ImageOptimizer::provideStreamData(QPDFObjGen const&, Pipeline* pipeline) } QPDFJob::PageSpec::PageSpec( - std::string const& filename, char const* password, std::string const& range) : + std::string const& filename, std::string const& password, std::string const& range) : filename(filename), + password(password.empty() ? "" : password), range(range) { - if (password) { - this->password = QUtil::make_shared_cstr(password); - } } QPDFPageData::QPDFPageData(std::string const& filename, QPDF* qpdf, std::string const& range) : @@ -396,7 +394,7 @@ QPDFJob::parseRotationParameter(std::string const& parameter) } else { angle_str = parameter; } - if (angle_str.length() > 0) { + if (!angle_str.empty()) { char first = angle_str.at(0); if ((first == '+') || (first == '-')) { relative = ((first == '+') ? 1 : -1); @@ -440,7 +438,7 @@ QPDFJob::createQPDF() checkConfiguration(); std::unique_ptr pdf_sp; try { - processFile(pdf_sp, m->infilename.get(), m->password.get(), true, true); + processFile(pdf_sp, m->infilename.data(), m->password.data(), true, true); } catch (QPDFExc& e) { if (e.getErrorCode() == qpdf_e_password) { // Allow certain operations to work when an incorrect password is supplied. @@ -561,7 +559,7 @@ QPDFJob::hasWarnings() const bool QPDFJob::createsOutput() const { - return ((m->outfilename != nullptr) || m->replace_input); + return (!m->outfilename.empty() || m->replace_input); } int @@ -604,34 +602,39 @@ QPDFJob::checkConfiguration() if (m->replace_input) { // Check for --empty appears later after we have checked m->infilename. - if (m->outfilename) { + if (!m->outfilename.empty()) { usage("--replace-input may not be used when an output file is specified"); - } else if (m->split_pages) { + } + if (m->split_pages) { usage("--split-pages may not be used with --replace-input"); - } else if (m->json_version) { + } + if (m->json_version) { usage("--json may not be used with --replace-input"); } } - if (m->json_version && (m->outfilename == nullptr)) { + if (m->json_version && m->outfilename.empty()) { // The output file is optional with --json for backward compatibility and defaults to // standard output. - m->outfilename = QUtil::make_shared_cstr("-"); + m->outfilename = "-"; } - if (m->infilename == nullptr) { + if (m->infilename.empty() && !m->empty_input) { usage("an input file name is required"); - } else if (m->replace_input && (strlen(m->infilename.get()) == 0)) { + } + if (m->replace_input && m->infilename.empty()) { usage("--replace-input may not be used with --empty"); - } else if (m->require_outfile && (m->outfilename == nullptr) && (!m->replace_input)) { + } + if (m->require_outfile && m->outfilename.empty() && !m->replace_input) { usage("an output file name is required; use - for standard output"); - } else if ((!m->require_outfile) && ((m->outfilename != nullptr) || m->replace_input)) { + } + if (!m->require_outfile && (!m->outfilename.empty() || m->replace_input)) { usage("no output file may be given for this option"); } if (m->check_requires_password && m->check_is_encrypted) { usage("--requires-password and --is-encrypted may not be given together"); } - if (m->encrypt && (!m->allow_insecure) && - (m->owner_password.empty() && (!m->user_password.empty()) && (m->keylen == 256))) { + if (m->encrypt && !m->allow_insecure && m->owner_password.empty() && + !m->user_password.empty() && m->keylen == 256) { // Note that empty owner passwords for R < 5 are copied from the user password, so this lack // of security is not an issue for those files. Also we are consider only the ability to // open the file without a password to be insecure. We are not concerned about whether the @@ -644,7 +647,7 @@ QPDFJob::checkConfiguration() } bool save_to_stdout = false; - if (m->require_outfile && m->outfilename && (strcmp(m->outfilename.get(), "-") == 0)) { + if (m->require_outfile && m->outfilename == "-") { if (m->split_pages) { usage("--split-pages may not be used when writing to standard output"); } @@ -656,7 +659,7 @@ QPDFJob::checkConfiguration() if (save_to_stdout) { m->log->saveToStandardOutput(true); } - if ((!m->split_pages) && QUtil::same_file(m->infilename.get(), m->outfilename.get())) { + if (!m->split_pages && QUtil::same_file(m->infilename.data(), m->outfilename.data())) { QTC::TC("qpdf", "QPDFJob same file error"); usage( "input file and output file are the same; use --replace-input to intentionally " @@ -664,11 +667,11 @@ QPDFJob::checkConfiguration() } if (m->json_version == 1) { - if (m->json_keys.count("qpdf")) { + if (m->json_keys.contains("qpdf")) { usage("json key \"qpdf\" is only valid for json version > 1"); } } else { - if (m->json_keys.count("objectinfo") || m->json_keys.count("objects")) { + if (m->json_keys.contains("objectinfo") || m->json_keys.contains("objects")) { usage("json keys \"objects\" and \"objectinfo\" are only valid for json version 1"); } } @@ -781,7 +784,7 @@ QPDFJob::doCheck(QPDF& pdf) // may continue to perform additional checks after finding errors. bool okay = true; auto& cout = *m->log->getInfo(); - cout << "checking " << m->infilename.get() << "\n"; + cout << "checking " << m->infilename << "\n"; QPDF::JobSetter::setCheckMode(pdf, true); try { int extension_level = pdf.getExtensionLevel(); @@ -942,7 +945,7 @@ QPDFJob::doListAttachments(QPDF& pdf) }); } } else { - *m->log->getInfo() << m->infilename.get() << " has no embedded files\n"; + *m->log->getInfo() << m->infilename << " has no embedded files\n"; } } @@ -1002,13 +1005,13 @@ QPDFJob::doJSONObjects(Pipeline* p, bool& first, QPDF& pdf) for (auto& obj: pdf.getAllObjects()) { std::string key = obj.unparse(); - if (all_objects || wanted_og.count(obj.getObjGen())) { + if (all_objects || wanted_og.contains(obj.getObjGen())) { JSON::writeDictionaryKey(p, first_object, obj.unparse(), 2); obj.writeJSON(1, p, true, 2); first_object = false; } } - if (all_objects || m->json_objects.count("trailer")) { + if (all_objects || m->json_objects.contains("trailer")) { JSON::writeDictionaryKey(p, first_object, "trailer", 2); pdf.getTrailer().writeJSON(1, p, true, 2); first_object = false; @@ -1016,7 +1019,7 @@ QPDFJob::doJSONObjects(Pipeline* p, bool& first, QPDF& pdf) JSON::writeDictionaryClose(p, first_object, 1); } else { std::set json_objects; - if (m->json_objects.count("trailer")) { + if (m->json_objects.contains("trailer")) { json_objects.insert("trailer"); } for (auto og: getWantedJSONObjects()) { @@ -1043,7 +1046,7 @@ QPDFJob::doJSONObjectinfo(Pipeline* p, bool& first, QPDF& pdf) bool all_objects = m->json_objects.empty(); auto wanted_og = getWantedJSONObjects(); for (auto& obj: pdf.getAllObjects()) { - if (all_objects || wanted_og.count(obj.getObjGen())) { + if (all_objects || wanted_og.contains(obj.getObjGen())) { auto j_details = JSON::makeDictionary(); auto j_stream = j_details.addDictionaryMember("stream", JSON::makeDictionary()); bool is_stream = obj.isStream(); @@ -1165,7 +1168,7 @@ QPDFJob::addOutlinesToJson( JSON j_destpage = JSON::makeNull(); if (page.isIndirect()) { QPDFObjGen og = page.getObjGen(); - if (page_numbers.count(og)) { + if (page_numbers.contains(og)) { j_destpage = JSON::makeInt(page_numbers[og]); } } @@ -1384,190 +1387,201 @@ QPDFJob::json_schema(int json_version, std::set* keys) // mismatch is a bug in qpdf. This helps to enforce our policy of consistently providing a known // structure where every documented key will always be present, which makes it easier to consume // our JSON. This is discussed in more depth in the manual. - JSON schema = JSON::makeDictionary(); - schema.addDictionaryMember( - "version", - JSON::makeString("JSON format serial number; increased for non-compatible changes")); - JSON j_params = schema.addDictionaryMember("parameters", JSON::parse(R"({ - "decodelevel": "decode level used to determine stream filterability" -})")); - bool all_keys = ((keys == nullptr) || keys->empty()); + static constexpr const char* objects_schema_v1 = R"({ + "": "json representation of object" + })"; - // The list of selectable top-level keys id duplicated in the following places: job.yml, - // QPDFJob::json_schema, and QPDFJob::doJSON. - if (json_version == 1) { - if (all_keys || keys->count("objects")) { - schema.addDictionaryMember("objects", JSON::parse(R"({ - "": "json representation of object" -})")); - } - if (all_keys || keys->count("objectinfo")) { - JSON objectinfo = schema.addDictionaryMember("objectinfo", JSON::parse(R"({ - "": { - "stream": { - "filter": "if stream, its filters, otherwise null", - "is": "whether the object is a stream", - "length": "if stream, its length, otherwise null" - } - } -})")); + static constexpr const char* objectinfo_schema_v1 = R"({ + "": { + "stream": { + "filter": "if stream, its filters, otherwise null", + "is": "whether the object is a stream", + "length": "if stream, its length, otherwise null" } - } else { - if (all_keys || keys->count("qpdf")) { - schema.addDictionaryMember("qpdf", JSON::parse(R"([{ - "jsonversion": "numeric JSON version", - "pdfversion": "PDF version as x.y", - "pushedinheritedpageresources": "whether inherited attributes were pushed to the page level", - "calledgetallpages": "whether getAllPages was called", - "maxobjectid": "highest object ID in output, ignored on input" -}, -{ - "": "json representation of object" -}])")); - } - } - if (all_keys || keys->count("pages")) { - JSON page = schema.addDictionaryMember("pages", JSON::parse(R"([ - { - "contents": [ - "reference to each content stream" - ], - "images": [ + } + })"; + + static constexpr const char* qpdf_schema = R"([{ + "jsonversion": "numeric JSON version", + "pdfversion": "PDF version as x.y", + "pushedinheritedpageresources": "whether inherited attributes were pushed to the page level", + "calledgetallpages": "whether getAllPages was called", + "maxobjectid": "highest object ID in output, ignored on input" + }, + { + "": "json representation of object" + }])"; + + static constexpr const char* pages_schema = R"([ { - "bitspercomponent": "bits per component", - "colorspace": "color space", - "decodeparms": [ - "decode parameters for image data" + "contents": [ + "reference to each content stream" + ], + "images": [ + { + "bitspercomponent": "bits per component", + "colorspace": "color space", + "decodeparms": [ + "decode parameters for image data" + ], + "filter": [ + "filters applied to image data" + ], + "filterable": "whether image data can be decoded using the decode level qpdf was invoked with", + "height": "image height", + "name": "name of image in XObject table", + "object": "reference to image stream", + "width": "image width" + } ], - "filter": [ - "filters applied to image data" + "label": "page label dictionary, or null if none", + "object": "reference to original page object", + "outlines": [ + { + "dest": "outline destination dictionary", + "object": "reference to outline that targets this page", + "title": "outline title" + } ], - "filterable": "whether image data can be decoded using the decode level qpdf was invoked with", - "height": "image height", - "name": "name of image in XObject table", - "object": "reference to image stream", - "width": "image width" + "pageposfrom1": "position of page in document numbering from 1" + } + ])"; + + static constexpr const char* pagelabels_schema = R"([ + { + "index": "starting page position starting from zero", + "label": "page label dictionary" } - ], - "label": "page label dictionary, or null if none", - "object": "reference to original page object", - "outlines": [ + ])"; + + static constexpr const char* outlines_schema = R"([ { "dest": "outline destination dictionary", - "object": "reference to outline that targets this page", + "destpageposfrom1": "position of destination page in document numbered from 1; null if not known", + "kids": "array of descendent outlines", + "object": "reference to this outline", + "open": "whether the outline is displayed expanded", "title": "outline title" } - ], - "pageposfrom1": "position of page in document numbering from 1" - } -])")); - } - if (all_keys || keys->count("pagelabels")) { - JSON labels = schema.addDictionaryMember("pagelabels", JSON::parse(R"([ - { - "index": "starting page position starting from zero", - "label": "page label dictionary" - } -])")); - } - if (all_keys || keys->count("outlines")) { - JSON outlines = schema.addDictionaryMember("outlines", JSON::parse(R"([ - { - "dest": "outline destination dictionary", - "destpageposfrom1": "position of destination page in document numbered from 1; null if not known", - "kids": "array of descendent outlines", - "object": "reference to this outline", - "open": "whether the outline is displayed expanded", - "title": "outline title" - } -])")); - } - if (all_keys || keys->count("acroform")) { - JSON acroform = schema.addDictionaryMember("acroform", JSON::parse(R"({ - "fields": [ - { - "alternativename": "alternative name of field -- this is the one usually shown to users", - "annotation": { - "annotationflags": "annotation flags from /F -- see pdf_annotation_flag_e in qpdf/Constants.h", - "appearancestate": "appearance state -- can be used to determine value for checkboxes and radio buttons", - "object": "reference to the annotation object" + ])"; + + static constexpr const char* acroform_schema = R"({ + "fields": [ + { + "alternativename": "alternative name of field -- this is the one usually shown to users", + "annotation": { + "annotationflags": "annotation flags from /F -- see pdf_annotation_flag_e in qpdf/Constants.h", + "appearancestate": "appearance state -- can be used to determine value for checkboxes and radio buttons", + "object": "reference to the annotation object" + }, + "choices": "for choices fields, the list of choices presented to the user", + "defaultvalue": "default value of field", + "fieldflags": "form field flags from /Ff -- see pdf_form_field_flag_e in qpdf/Constants.h", + "fieldtype": "field type", + "fullname": "full name of field", + "ischeckbox": "whether field is a checkbox", + "ischoice": "whether field is a list, combo, or dropdown", + "isradiobutton": "whether field is a radio button -- buttons in a single group share a parent", + "istext": "whether field is a text field", + "mappingname": "mapping name of field", + "object": "reference to this form field", + "pageposfrom1": "position of containing page numbered from 1", + "parent": "reference to this field's parent", + "partialname": "partial name of field", + "quadding": "field quadding -- number indicating left, center, or right", + "value": "value of field" + } + ], + "hasacroform": "whether the document has interactive forms", + "needappearances": "whether the form fields' appearance streams need to be regenerated" + })"; + + static constexpr const char* encrypt_schema1 = R"({ + "capabilities": { + "accessibility": "allow extraction for accessibility?", + "extract": "allow extraction?", + ")"; + + static constexpr const char* encrypt_schema2 = R"(": "allow modifying annotations?", + "modify": "allow all modifications?", + "modifyassembly": "allow modifying document assembly?", + "modifyforms": "allow modifying forms?", + "modifyother": "allow other modifications?", + "printhigh": "allow high resolution printing?", + "printlow": "allow low resolution printing?" + }, + "encrypted": "whether the document is encrypted", + "ownerpasswordmatched": "whether supplied password matched owner password; always false for non-encrypted files", + "recovereduserpassword": "If the owner password was used to recover the user password, reveal user password; otherwise null", + "parameters": { + "P": "P value from Encrypt dictionary", + "R": "R value from Encrypt dictionary", + "V": "V value from Encrypt dictionary", + "bits": "encryption key bit length", + "filemethod": "encryption method for attachments", + "key": "encryption key; will be null unless --show-encryption-key was specified", + "method": "overall encryption method: none, mixed, RC4, AESv2, AESv3", + "streammethod": "encryption method for streams", + "stringmethod": "encryption method for string" }, - "choices": "for choices fields, the list of choices presented to the user", - "defaultvalue": "default value of field", - "fieldflags": "form field flags from /Ff -- see pdf_form_field_flag_e in qpdf/Constants.h", - "fieldtype": "field type", - "fullname": "full name of field", - "ischeckbox": "whether field is a checkbox", - "ischoice": "whether field is a list, combo, or dropdown", - "isradiobutton": "whether field is a radio button -- buttons in a single group share a parent", - "istext": "whether field is a text field", - "mappingname": "mapping name of field", - "object": "reference to this form field", - "pageposfrom1": "position of containing page numbered from 1", - "parent": "reference to this field's parent", - "partialname": "partial name of field", - "quadding": "field quadding -- number indicating left, center, or right", - "value": "value of field" - } - ], - "hasacroform": "whether the document has interactive forms", - "needappearances": "whether the form fields' appearance streams need to be regenerated" + "userpasswordmatched": "whether supplied password matched user password; always false for non-encrypted files" + })"; + + static constexpr const char* attachments_schema = R"({ + "": { + "filespec": "object containing the file spec", + "preferredcontents": "most preferred embedded file stream", + "preferredname": "most preferred file name", + "description": "description of attachment", + "names": { + "": "file name for key" + }, + "streams": { + "": { + "creationdate": "ISO-8601 creation date or null", + "modificationdate": "ISO-8601 modification date or null", + "mimetype": "mime type or null", + "checksum": "MD5 checksum or null" + } + } + } + })"; + + JSON schema = JSON::makeDictionary(); + schema.addDictionaryMember( + "version", + JSON::makeString("JSON format serial number; increased for non-compatible changes")); + JSON j_params = schema.addDictionaryMember("parameters", JSON::parse(R"({ + "decodelevel": "decode level used to determine stream filterability" })")); + + const bool all_keys = !keys || keys->empty(); + + auto add_if_want_key = [&](std::string const& key, std::string const& json) -> void { + if (all_keys || keys->contains(key)) { + (void)schema.addDictionaryMember(key, JSON::parse(json)); + } + }; + + // The list of selectable top-level keys id duplicated in the following places: job.yml, + // QPDFJob::json_schema, and QPDFJob::doJSON. + if (json_version == 1) { + add_if_want_key("objects", objects_schema_v1); + add_if_want_key("objectinfo", objectinfo_schema_v1); + } else { + add_if_want_key("qpdf", qpdf_schema); } + add_if_want_key("pages", pages_schema); + add_if_want_key("pagelabels", pagelabels_schema); + add_if_want_key("outlines", outlines_schema); + add_if_want_key("acroform", acroform_schema); + std::string MODIFY_ANNOTATIONS = (json_version == 1 ? "moddifyannotations" : "modifyannotations"); - if (all_keys || keys->count("encrypt")) { - JSON encrypt = schema.addDictionaryMember("encrypt", JSON::parse(R"({ - "capabilities": { - "accessibility": "allow extraction for accessibility?", - "extract": "allow extraction?", - ")" + MODIFY_ANNOTATIONS + R"(": "allow modifying annotations?", - "modify": "allow all modifications?", - "modifyassembly": "allow modifying document assembly?", - "modifyforms": "allow modifying forms?", - "modifyother": "allow other modifications?", - "printhigh": "allow high resolution printing?", - "printlow": "allow low resolution printing?" - }, - "encrypted": "whether the document is encrypted", - "ownerpasswordmatched": "whether supplied password matched owner password; always false for non-encrypted files", - "recovereduserpassword": "If the owner password was used to recover the user password, reveal user password; otherwise null", - "parameters": { - "P": "P value from Encrypt dictionary", - "R": "R value from Encrypt dictionary", - "V": "V value from Encrypt dictionary", - "bits": "encryption key bit length", - "filemethod": "encryption method for attachments", - "key": "encryption key; will be null unless --show-encryption-key was specified", - "method": "overall encryption method: none, mixed, RC4, AESv2, AESv3", - "streammethod": "encryption method for streams", - "stringmethod": "encryption method for string" - }, - "userpasswordmatched": "whether supplied password matched user password; always false for non-encrypted files" -})")); - } - if (all_keys || keys->count("attachments")) { - JSON attachments = schema.addDictionaryMember("attachments", JSON::parse(R"({ - "": { - "filespec": "object containing the file spec", - "preferredcontents": "most preferred embedded file stream", - "preferredname": "most preferred file name", - "description": "description of attachment", - "names": { - "": "file name for key" - }, - "streams": { - "": { - "creationdate": "ISO-8601 creation date or null", - "modificationdate": "ISO-8601 modification date or null", - "mimetype": "mime type or null", - "checksum": "MD5 checksum or null" - } - } - } -})")); - } + add_if_want_key("encrypt", encrypt_schema1 + MODIFY_ANNOTATIONS + encrypt_schema2); + add_if_want_key("attachments", attachments_schema); + return schema; } @@ -1590,9 +1604,9 @@ QPDFJob::doJSON(QPDF& pdf, Pipeline* p) // are reserved for users. std::string captured_json; - std::shared_ptr pl_str; + std::unique_ptr pl_str; if (m->test_json_schema) { - pl_str = std::make_shared("capture json", p, captured_json); + pl_str = std::make_unique("capture json", p, captured_json); p = pl_str.get(); } @@ -1626,43 +1640,49 @@ QPDFJob::doJSON(QPDF& pdf, Pipeline* p) j_params.addDictionaryMember("decodelevel", JSON::makeString(decode_level_str)); JSON::writeDictionaryItem(p, first, "parameters", j_params, 1); } - bool all_keys = m->json_keys.empty(); + + const bool all_keys = m->json_keys.empty(); + + auto want_key = [&](std::string const& key) -> bool { + return all_keys || m->json_keys.contains(key); + }; + // The list of selectable top-level keys id duplicated in the following places: job.yml, // QPDFJob::json_schema, and QPDFJob::doJSON. // We do pages and pagelabels first since they have the side effect of repairing the pages tree, // which could potentially impact object references in remaining items. - if (all_keys || m->json_keys.count("pages")) { + if (want_key("pages")) { doJSONPages(p, first, pdf); } - if (all_keys || m->json_keys.count("pagelabels")) { + if (want_key("pagelabels")) { doJSONPageLabels(p, first, pdf); } // The non-special keys are output in alphabetical order, but the order doesn't actually matter. - if (all_keys || m->json_keys.count("acroform")) { + if (want_key("acroform")) { doJSONAcroform(p, first, pdf); } - if (all_keys || m->json_keys.count("attachments")) { + if (want_key("attachments")) { doJSONAttachments(p, first, pdf); } - if (all_keys || m->json_keys.count("encrypt")) { + if (want_key("encrypt")) { doJSONEncrypt(p, first, pdf); } - if (all_keys || m->json_keys.count("outlines")) { + if (want_key("outlines")) { doJSONOutlines(p, first, pdf); } // We do objects last so their information is consistent with repairing the page tree. To see // the original file with any page tree problems and the page tree not flattened, select // qpdf/objects/objectinfo without other keys. - if (all_keys || m->json_keys.count("objects") || m->json_keys.count("qpdf")) { + if (want_key("objects") || want_key("qpdf")) { doJSONObjects(p, first, pdf); } if (m->json_version == 1) { // "objectinfo" is not needed for version >1 since you can tell streams from other objects // in "objects". - if (all_keys || m->json_keys.count("objectinfo")) { + if (want_key("objectinfo")) { doJSONObjectinfo(p, first, pdf); } } @@ -1700,9 +1720,9 @@ QPDFJob::doInspection(QPDF& pdf) } if (m->check_linearization) { if (!pdf.isLinearized()) { - cout << m->infilename.get() << " is not linearized\n"; + cout << m->infilename << " is not linearized\n"; } else if (pdf.checkLinearization()) { - cout << m->infilename.get() << ": no linearization errors\n"; + cout << m->infilename << ": no linearization errors\n"; } else { m->warnings = true; } @@ -1711,7 +1731,7 @@ QPDFJob::doInspection(QPDF& pdf) if (pdf.isLinearized()) { pdf.showLinearizationData(); } else { - cout << m->infilename.get() << " is not linearized\n"; + cout << m->infilename << " is not linearized\n"; } } if (m->show_xref) { @@ -1748,7 +1768,7 @@ QPDFJob::doProcessOnce( if (empty) { pdf->emptyPDF(); } else if (main_input && m->json_input) { - pdf->createFromJSON(m->infilename.get()); + pdf->createFromJSON(m->infilename); } else { fn(pdf.get(), password); } @@ -1862,7 +1882,7 @@ QPDFJob::validateUnderOverlay(QPDF& pdf, UnderOverlay* uo) { QPDFPageDocumentHelper main_pdh(pdf); int main_npages = QIntC::to_int(main_pdh.getAllPages().size()); - processFile(uo->pdf, uo->filename.c_str(), uo->password.get(), true, false); + processFile(uo->pdf, uo->filename.data(), uo->password.data(), true, false); QPDFPageDocumentHelper uo_pdh(*(uo->pdf)); int uo_npages = QIntC::to_int(uo_pdh.getAllPages().size()); try { @@ -1891,7 +1911,7 @@ get_afdh_for_qpdf( std::map>& afdh_map, QPDF* q) { auto uid = q->getUniqueId(); - if (!afdh_map.count(uid)) { + if (!afdh_map.contains(uid)) { afdh_map[uid] = std::make_shared(*q); } return afdh_map[uid].get(); @@ -1909,7 +1929,7 @@ QPDFJob::doUnderOverlayForPage( QPDFPageObjectHelper& dest_page) { int pageno = 1 + QIntC::to_int(page_idx); - if (!(pagenos.count(pageno) && pagenos[pageno].count(uo_idx))) { + if (!(pagenos.contains(pageno) && pagenos[pageno].contains(uo_idx))) { return ""; } @@ -1928,7 +1948,7 @@ QPDFJob::doUnderOverlayForPage( v << " " << uo.filename << " " << uo.which << " " << from_pageno << "\n"; }); auto from_page = pages.at(QIntC::to_size(from_pageno - 1)); - if (fo[from_pageno].count(uo_idx) == 0) { + if (!fo[from_pageno].contains(uo_idx)) { fo[from_pageno][uo_idx] = pdf.copyForeignObject(from_page.getFormXObjectForPage()); } @@ -2410,7 +2430,7 @@ QPDFJob::handlePageSpecs(QPDF& pdf, std::vector>& page_hea // Handle "." as a shortcut for the input file for (auto& page_spec: m->page_specs) { if (page_spec.filename == ".") { - page_spec.filename = m->infilename.get(); + page_spec.filename = m->infilename; } if (page_spec.range.empty()) { page_spec.range = "1-z"; @@ -2436,11 +2456,11 @@ QPDFJob::handlePageSpecs(QPDF& pdf, std::vector>& page_hea // Create a QPDF object for each file that we may take pages from. std::map page_spec_qpdfs; std::map page_spec_cfis; - page_spec_qpdfs[m->infilename.get()] = &pdf; + page_spec_qpdfs[m->infilename] = &pdf; std::vector parsed_specs; std::map> copied_pages; for (auto& page_spec: m->page_specs) { - if (page_spec_qpdfs.count(page_spec.filename) == 0) { + if (!page_spec_qpdfs.contains(page_spec.filename)) { // Open the PDF file and store the QPDF object. Throw a std::shared_ptr to the qpdf into // a heap so that it survives through copying to the output but gets cleaned up // automatically at the end. Do not canonicalize the file name. Using two different @@ -2448,11 +2468,11 @@ QPDFJob::handlePageSpecs(QPDF& pdf, std::vector>& page_hea // you are using this an example of how to do this with the API, you can just create two // different QPDF objects to the same underlying file with the same path to achieve the // same effect. - char const* password = page_spec.password.get(); - if ((!m->encryption_file.empty()) && (password == nullptr) && - (page_spec.filename == m->encryption_file)) { + auto password = page_spec.password; + if (!m->encryption_file.empty() && password.empty() && + page_spec.filename == m->encryption_file) { QTC::TC("qpdf", "QPDFJob pages encryption password"); - password = m->encryption_file_password.get(); + password = m->encryption_file_password; } doIfVerbose([&](Pipeline& v, std::string const& prefix) { v << prefix << ": processing " << page_spec.filename << "\n"; @@ -2470,7 +2490,7 @@ QPDFJob::handlePageSpecs(QPDF& pdf, std::vector>& page_hea is = std::shared_ptr(fis); } std::unique_ptr qpdf_sp; - processInputSource(qpdf_sp, is, password, true); + processInputSource(qpdf_sp, is, password.data(), true); page_spec_qpdfs[page_spec.filename] = qpdf_sp.get(); page_heap.push_back(std::move(qpdf_sp)); if (cis) { @@ -2490,13 +2510,13 @@ QPDFJob::handlePageSpecs(QPDF& pdf, std::vector>& page_hea for (auto const& iter: page_spec_qpdfs) { std::string const& filename = iter.first; ClosedFileInputSource* cis = nullptr; - if (page_spec_cfis.count(filename)) { + if (page_spec_cfis.contains(filename)) { cis = page_spec_cfis[filename]; cis->stayOpen(true); } QPDF& other(*(iter.second)); auto other_uuid = other.getUniqueId(); - if (remove_unreferenced.count(other_uuid) == 0) { + if (!remove_unreferenced.contains(other_uuid)) { remove_unreferenced[other_uuid] = shouldRemoveUnreferencedResources(other); } if (cis) { @@ -2563,7 +2583,7 @@ QPDFJob::handlePageSpecs(QPDF& pdf, std::vector>& page_hea std::set referenced_fields; for (auto& page_data: parsed_specs) { ClosedFileInputSource* cis = nullptr; - if (page_spec_cfis.count(page_data.filename)) { + if (page_spec_cfis.contains(page_data.filename)) { cis = page_spec_cfis[page_data.filename]; cis->stayOpen(true); } @@ -2582,7 +2602,7 @@ QPDFJob::handlePageSpecs(QPDF& pdf, std::vector>& page_hea QPDFPageObjectHelper to_copy = page_data.orig_pages.at(QIntC::to_size(pageno)); QPDFObjGen to_copy_og = to_copy.getObjectHandle().getObjGen(); unsigned long long from_uuid = page_data.qpdf->getUniqueId(); - if (copied_pages[from_uuid].count(to_copy_og)) { + if (copied_pages[from_uuid].contains(to_copy_og)) { QTC::TC( "qpdf", "QPDFJob copy same page more than once", @@ -2600,7 +2620,7 @@ QPDFJob::handlePageSpecs(QPDF& pdf, std::vector>& page_hea if (this_file) { // This is a page from the original file. Keep track of the fact that we are using // it. - first_copy_from_orig = (selected_from_orig.count(pageno) == 0); + first_copy_from_orig = (!selected_from_orig.contains(pageno)); selected_from_orig.insert(pageno); } auto new_page = added_page(pdf, to_copy); @@ -2645,7 +2665,7 @@ QPDFJob::handlePageSpecs(QPDF& pdf, std::vector>& page_hea // sure we keep form fields from pages we preserved. for (size_t pageno = 0; pageno < orig_pages.size(); ++pageno) { auto page = orig_pages.at(pageno); - if (selected_from_orig.count(QIntC::to_int(pageno))) { + if (selected_from_orig.contains(QIntC::to_int(pageno))) { for (auto field: this_afdh->getFormFieldsForPage(page)) { QTC::TC("qpdf", "QPDFJob pages keeping field from original"); referenced_fields.insert(field.getObjectHandle().getObjGen()); @@ -2664,7 +2684,7 @@ QPDFJob::handlePageSpecs(QPDF& pdf, std::vector>& page_hea new_fields = pdf.makeIndirectObject(new_fields); } for (auto const& field: fields.aitems()) { - if (referenced_fields.count(field.getObjGen())) { + if (referenced_fields.contains(field.getObjGen())) { new_fields.appendItem(field); } } @@ -2940,8 +2960,8 @@ QPDFJob::setWriterOptions(QPDFWriter& w) std::unique_ptr encryption_pdf; processFile( encryption_pdf, - m->encryption_file.c_str(), - m->encryption_file_password.get(), + m->encryption_file.data(), + m->encryption_file_password.data(), false, false); w.copyEncryptionParameters(*encryption_pdf); @@ -2977,7 +2997,8 @@ QPDFJob::setWriterOptions(QPDFWriter& w) std::shared_ptr( new QPDFWriter::FunctionProgressReporter(m->progress_handler))); } else { - char const* outfilename = m->outfilename ? m->outfilename.get() : "standard output"; + char const* outfilename = + !m->outfilename.empty() ? m->outfilename.data() : "standard output"; w.registerProgressReporter( std::shared_ptr( // line-break @@ -2992,20 +3013,20 @@ QPDFJob::doSplitPages(QPDF& pdf) // Generate output file pattern std::string before; std::string after; - size_t len = strlen(m->outfilename.get()); - char* num_spot = strstr(const_cast(m->outfilename.get()), "%d"); - if (num_spot != nullptr) { + size_t len = m->outfilename.size(); + auto num_spot = m->outfilename.find("%d"); + if (num_spot != std::string::npos) { QTC::TC("qpdf", "QPDFJob split-pages %d"); - before = std::string(m->outfilename.get(), QIntC::to_size(num_spot - m->outfilename.get())); - after = num_spot + 2; + before = m->outfilename.substr(0, num_spot); + after = m->outfilename.substr(num_spot + 2); } else if ( - (len >= 4) && (QUtil::str_compare_nocase(m->outfilename.get() + len - 4, ".pdf") == 0)) { + len >= 4 && QUtil::str_compare_nocase(m->outfilename.substr(len - 4).data(), ".pdf") == 0) { QTC::TC("qpdf", "QPDFJob split-pages .pdf"); - before = std::string(m->outfilename.get(), len - 4) + "-"; - after = m->outfilename.get() + len - 4; + before = std::string(m->outfilename.data(), len - 4) + "-"; + after = m->outfilename.data() + len - 4; } else { QTC::TC("qpdf", "QPDFJob split-pages other"); - before = std::string(m->outfilename.get()) + "-"; + before = m->outfilename + "-"; } if (shouldRemoveUnreferencedResources(pdf)) { @@ -3064,7 +3085,7 @@ QPDFJob::doSplitPages(QPDF& pdf) page_range += "-" + QUtil::uint_to_string(last, QIntC::to_int(pageno_len)); } std::string outfile = before + page_range + after; - if (QUtil::same_file(m->infilename.get(), outfile.c_str())) { + if (QUtil::same_file(m->infilename.data(), outfile.data())) { throw std::runtime_error("split pages would overwrite input file with " + outfile); } QPDFWriter w(outpdf, outfile.c_str()); @@ -3079,15 +3100,15 @@ QPDFJob::doSplitPages(QPDF& pdf) void QPDFJob::writeOutfile(QPDF& pdf) { - std::shared_ptr temp_out; + std::string temp_out; if (m->replace_input) { // Append but don't prepend to the path to generate a temporary name. This saves us from // having to split the path by directory and non-directory. - temp_out = QUtil::make_shared_cstr(std::string(m->infilename.get()) + ".~qpdf-temp#"); + temp_out = m->infilename + ".~qpdf-temp#"; // m->outfilename will be restored to 0 before temp_out goes out of scope. m->outfilename = temp_out; - } else if (strcmp(m->outfilename.get(), "-") == 0) { - m->outfilename = nullptr; + } else if (m->outfilename == "-") { + m->outfilename.clear(); } if (m->json_version) { writeJSON(pdf); @@ -3095,8 +3116,8 @@ QPDFJob::writeOutfile(QPDF& pdf) // QPDFWriter must have block scope so the output file will be closed after write() // finishes. QPDFWriter w(pdf); - if (m->outfilename) { - w.setOutputFilename(m->outfilename.get()); + if (!m->outfilename.empty()) { + w.setOutputFilename(m->outfilename.data()); } else { // saveToStandardOutput has already been called, but calling it again is defensive and // harmless. @@ -3106,24 +3127,24 @@ QPDFJob::writeOutfile(QPDF& pdf) setWriterOptions(w); w.write(); } - if (m->outfilename) { + if (!m->outfilename.empty()) { doIfVerbose([&](Pipeline& v, std::string const& prefix) { - v << prefix << ": wrote file " << m->outfilename.get() << "\n"; + v << prefix << ": wrote file " << m->outfilename << "\n"; }); } if (m->replace_input) { - m->outfilename = nullptr; + m->outfilename.clear(); } if (m->replace_input) { // We must close the input before we can rename files pdf.closeInputSource(); - std::string backup = std::string(m->infilename.get()) + ".~qpdf-orig"; + std::string backup = m->infilename + ".~qpdf-orig"; bool warnings = pdf.anyWarnings(); if (!warnings) { backup.append(1, '#'); } - QUtil::rename_file(m->infilename.get(), backup.c_str()); - QUtil::rename_file(temp_out.get(), m->infilename.get()); + QUtil::rename_file(m->infilename.data(), backup.data()); + QUtil::rename_file(temp_out.data(), m->infilename.data()); if (warnings) { *m->log->getError() << m->message_prefix << ": there are warnings; original file kept in " << backup << "\n"; @@ -3145,12 +3166,12 @@ QPDFJob::writeJSON(QPDF& pdf) // File pipeline must have block scope so it will be closed after write. std::shared_ptr fc; std::shared_ptr fp; - if (m->outfilename.get()) { + if (!m->outfilename.empty()) { QTC::TC("qpdf", "QPDFJob write json to file"); if (m->json_stream_prefix.empty()) { - m->json_stream_prefix = m->outfilename.get(); + m->json_stream_prefix = m->outfilename; } - fc = std::make_shared(QUtil::safe_fopen(m->outfilename.get(), "w")); + fc = std::make_shared(QUtil::safe_fopen(m->outfilename.data(), "w")); fp = std::make_shared("json output", fc->f); } else if ((m->json_stream_data == qpdf_sj_file) && m->json_stream_prefix.empty()) { QTC::TC("qpdf", "QPDFJob need json-stream-prefix for stdout"); diff --git a/libqpdf/QPDFJob_argv.cc b/libqpdf/QPDFJob_argv.cc index 180a7a6..f49b7b5 100644 --- a/libqpdf/QPDFJob_argv.cc +++ b/libqpdf/QPDFJob_argv.cc @@ -58,25 +58,25 @@ void ArgParser::initOptionTables() { #include - this->ap.addFinalCheck([this]() { c_main->checkConfiguration(); }); + ap.addFinalCheck([this]() { c_main->checkConfiguration(); }); // add_help is defined in auto_job_help.hh - add_help(this->ap); + add_help(ap); // Special case: ignore -- at the top level. This undocumented behavior is for backward // compatibility; it was unintentionally the case prior to 10.6, and some users were relying on // it. - this->ap.selectMainOptionTable(); - this->ap.addBare("--", []() {}); + ap.selectMainOptionTable(); + ap.addBare("--", []() {}); } void ArgParser::argPositional(std::string const& arg) { - if (!this->gave_input) { + if (!gave_input) { c_main->inputFile(arg); - this->gave_input = true; - } else if (!this->gave_output) { + gave_input = true; + } else if (!gave_output) { c_main->outputFile(arg); - this->gave_output = true; + gave_output = true; } else { usage("unknown argument " + arg); } @@ -86,20 +86,20 @@ void ArgParser::argEmpty() { c_main->emptyInput(); - this->gave_input = true; + gave_input = true; } void ArgParser::argReplaceInput() { c_main->replaceInput(); - this->gave_output = true; + gave_output = true; } void ArgParser::argVersion() { - auto whoami = this->ap.getProgname(); + auto whoami = ap.getProgname(); *QPDFLogger::defaultLogger()->getInfo() << whoami << " version " << QPDF::QPDFVersion() << "\n" << "Run " << whoami << " --copyright to see copyright and license information.\n"; @@ -136,7 +136,7 @@ ArgParser::argCopyright() // 1 2 3 4 5 6 7 8 // 12345678901234567890123456789012345678901234567890123456789012345678901234567890 *QPDFLogger::defaultLogger()->getInfo() - << this->ap.getProgname() + << ap.getProgname() << " version " << QPDF::QPDFVersion() << "\n" << "\n" << "Copyright (c) 2005-2021 Jay Berkenbilt\n" @@ -190,9 +190,9 @@ ArgParser::argShowCrypto() void ArgParser::argEncrypt() { - this->c_enc = c_main->encrypt(0, "", ""); - this->accumulated_args.clear(); - this->ap.selectOptionTable(O_ENCRYPTION); + c_enc = c_main->encrypt(0, "", ""); + accumulated_args.clear(); + ap.selectOptionTable(O_ENCRYPTION); } void @@ -202,14 +202,14 @@ ArgParser::argEncPositional(std::string const& arg) usage("positional and dashed encryption arguments may not be mixed"); } - this->accumulated_args.push_back(arg); - if (this->accumulated_args.size() < 3) { + accumulated_args.push_back(arg); + if (accumulated_args.size() < 3) { return; } - user_password = this->accumulated_args.at(0); - owner_password = this->accumulated_args.at(1); - auto len_str = this->accumulated_args.at(2); - this->accumulated_args.clear(); + user_password = accumulated_args.at(0); + owner_password = accumulated_args.at(1); + auto len_str = accumulated_args.at(2); + accumulated_args.clear(); argEncBits(len_str); } @@ -219,8 +219,8 @@ ArgParser::argEncUserPassword(std::string const& arg) if (!accumulated_args.empty()) { usage("positional and dashed encryption arguments may not be mixed"); } - this->used_enc_password_args = true; - this->user_password = arg; + used_enc_password_args = true; + user_password = arg; } void @@ -229,8 +229,8 @@ ArgParser::argEncOwnerPassword(std::string const& arg) if (!accumulated_args.empty()) { usage("positional and dashed encryption arguments may not be mixed"); } - this->used_enc_password_args = true; - this->owner_password = arg; + used_enc_password_args = true; + owner_password = arg; } void @@ -242,25 +242,25 @@ ArgParser::argEncBits(std::string const& arg) int keylen = 0; if (arg == "40") { keylen = 40; - this->ap.selectOptionTable(O_40_BIT_ENCRYPTION); + ap.selectOptionTable(O_40_BIT_ENCRYPTION); } else if (arg == "128") { keylen = 128; - this->ap.selectOptionTable(O_128_BIT_ENCRYPTION); + ap.selectOptionTable(O_128_BIT_ENCRYPTION); } else if (arg == "256") { keylen = 256; - this->ap.selectOptionTable(O_256_BIT_ENCRYPTION); + ap.selectOptionTable(O_256_BIT_ENCRYPTION); } else { usage("encryption key length must be 40, 128, or 256"); } - this->c_enc = c_main->encrypt(keylen, user_password, owner_password); + c_enc = c_main->encrypt(keylen, user_password, owner_password); } void ArgParser::argPages() { - this->accumulated_args.clear(); - this->c_pages = c_main->pages(); - this->ap.selectOptionTable(O_PAGES); + accumulated_args.clear(); + c_pages = c_main->pages(); + ap.selectOptionTable(O_PAGES); } void @@ -308,29 +308,29 @@ ArgParser::argEndPages() void ArgParser::argUnderlay() { - this->c_uo = c_main->underlay(); - this->ap.selectOptionTable(O_UNDERLAY_OVERLAY); + c_uo = c_main->underlay(); + ap.selectOptionTable(O_UNDERLAY_OVERLAY); } void ArgParser::argOverlay() { - this->c_uo = c_main->overlay(); - this->ap.selectOptionTable(O_UNDERLAY_OVERLAY); + c_uo = c_main->overlay(); + ap.selectOptionTable(O_UNDERLAY_OVERLAY); } void ArgParser::argAddAttachment() { - this->c_att = c_main->addAttachment(); - this->ap.selectOptionTable(O_ATTACHMENT); + c_att = c_main->addAttachment(); + ap.selectOptionTable(O_ATTACHMENT); } void ArgParser::argCopyAttachmentsFrom() { - this->c_copy_att = c_main->copyAttachmentsFrom(); - this->ap.selectOptionTable(O_COPY_ATTACHMENT); + c_copy_att = c_main->copyAttachmentsFrom(); + ap.selectOptionTable(O_COPY_ATTACHMENT); } void @@ -400,7 +400,7 @@ ArgParser::argEndCopyAttachment() void ArgParser::argSetPageLabels() { - this->ap.selectOptionTable(O_SET_PAGE_LABELS); + ap.selectOptionTable(O_SET_PAGE_LABELS); accumulated_args.clear(); } @@ -427,14 +427,14 @@ ArgParser::argJobJsonHelp() void ArgParser::usage(std::string const& message) { - this->ap.usage(message); + ap.usage(message); } void ArgParser::parseOptions() { try { - this->ap.parseArgs(); + ap.parseArgs(); } catch (std::runtime_error& e) { usage(e.what()); } diff --git a/libqpdf/QPDFJob_config.cc b/libqpdf/QPDFJob_config.cc index 2aff98c..f94d52d 100644 --- a/libqpdf/QPDFJob_config.cc +++ b/libqpdf/QPDFJob_config.cc @@ -15,8 +15,8 @@ QPDFJob::Config::checkConfiguration() QPDFJob::Config* QPDFJob::Config::inputFile(std::string const& filename) { - if (o.m->infilename == nullptr) { - o.m->infilename = QUtil::make_shared_cstr(filename); + if (o.m->infilename.empty()) { + o.m->infilename = filename; } else { usage("input file has already been given"); } @@ -26,13 +26,13 @@ QPDFJob::Config::inputFile(std::string const& filename) QPDFJob::Config* QPDFJob::Config::emptyInput() { - if (o.m->infilename == nullptr) { - // Various places in QPDFJob.cc know that the empty string for infile means empty. We set it - // to something other than a null pointer as an indication that some input source has been - // specified. This approach means that passing "" as the argument to inputFile in job JSON, - // or equivalently using "" as a positional command-line argument would be the same as - // --empty. This probably isn't worth blocking or coding around. - o.m->infilename = QUtil::make_shared_cstr(""); + if (o.m->infilename.empty()) { + // Various places in QPDFJob.cc used to know that the empty string for infile means empty. + // This approach meant that passing "" as the argument to inputFile in job JSON, or + // equivalently using "" as a positional command-line argument would be the same as + // --empty. This was deemed to be not worth blocking or coding around. This no longer holds + // from 12.3. + o.m->empty_input = true; } else { usage("empty input can't be used since input file has already been given"); } @@ -42,8 +42,8 @@ QPDFJob::Config::emptyInput() QPDFJob::Config* QPDFJob::Config::outputFile(std::string const& filename) { - if ((o.m->outfilename == nullptr) && (!o.m->replace_input)) { - o.m->outfilename = QUtil::make_shared_cstr(filename); + if (o.m->outfilename.empty() && !o.m->replace_input) { + o.m->outfilename = filename; } else { usage("output file has already been given"); } @@ -53,7 +53,7 @@ QPDFJob::Config::outputFile(std::string const& filename) QPDFJob::Config* QPDFJob::Config::replaceInput() { - if ((o.m->outfilename == nullptr) && (!o.m->replace_input)) { + if (o.m->outfilename.empty() && !o.m->replace_input) { o.m->replace_input = true; } else { usage("replace-input can't be used since output file has already been given"); @@ -175,7 +175,7 @@ QPDFJob::Config::deterministicId() QPDFJob::Config* QPDFJob::Config::encryptionFilePassword(std::string const& parameter) { - o.m->encryption_file_password = QUtil::make_shared_cstr(parameter); + o.m->encryption_file_password = parameter; return this; } @@ -456,7 +456,7 @@ QPDFJob::Config::optimizeImages() QPDFJob::Config* QPDFJob::Config::password(std::string const& parameter) { - o.m->password = QUtil::make_shared_cstr(parameter); + o.m->password = parameter; return this; } @@ -696,12 +696,12 @@ QPDFJob::Config::passwordFile(std::string const& parameter) QTC::TC("qpdf", "QPDFJob_config password file"); lines = QUtil::read_lines_from_file(parameter.c_str()); } - if (lines.size() >= 1) { - o.m->password = QUtil::make_shared_cstr(lines.front()); + if (!lines.empty()) { + o.m->password = lines.front(); if (lines.size() > 1) { *QPDFLogger::defaultLogger()->getError() - << this->o.m->message_prefix << ": WARNING: all but the first line of" + << o.m->message_prefix << ": WARNING: all but the first line of" << " the password file are ignored\n"; } } @@ -806,7 +806,7 @@ QPDFJob::Config::jobJsonFile(std::string const& parameter) } catch (std::exception& e) { throw std::runtime_error( "error with job-json file " + std::string(parameter) + ": " + e.what() + "\nRun " + - this->o.m->message_prefix + " --job-json-help for information on the file format."); + o.m->message_prefix + " --job-json-help for information on the file format."); } return this; } @@ -832,32 +832,32 @@ QPDFJob::CopyAttConfig::CopyAttConfig(Config* c) : QPDFJob::CopyAttConfig* QPDFJob::CopyAttConfig::file(std::string const& parameter) { - this->caf.path = parameter; + caf.path = parameter; return this; } QPDFJob::CopyAttConfig* QPDFJob::CopyAttConfig::prefix(std::string const& parameter) { - this->caf.prefix = parameter; + caf.prefix = parameter; return this; } QPDFJob::CopyAttConfig* QPDFJob::CopyAttConfig::password(std::string const& parameter) { - this->caf.password = parameter; + caf.password = parameter; return this; } QPDFJob::Config* QPDFJob::CopyAttConfig::endCopyAttachmentsFrom() { - if (this->caf.path.empty()) { + if (caf.path.empty()) { usage("copy attachments: no file specified"); } - this->config->o.m->attachments_to_copy.push_back(this->caf); - return this->config; + config->o.m->attachments_to_copy.push_back(caf); + return config; } QPDFJob::AttConfig::AttConfig(Config* c) : @@ -874,21 +874,21 @@ QPDFJob::Config::addAttachment() QPDFJob::AttConfig* QPDFJob::AttConfig::file(std::string const& parameter) { - this->att.path = parameter; + att.path = parameter; return this; } QPDFJob::AttConfig* QPDFJob::AttConfig::key(std::string const& parameter) { - this->att.key = parameter; + att.key = parameter; return this; } QPDFJob::AttConfig* QPDFJob::AttConfig::filename(std::string const& parameter) { - this->att.filename = parameter; + att.filename = parameter; return this; } @@ -898,7 +898,7 @@ QPDFJob::AttConfig::creationdate(std::string const& parameter) if (!QUtil::pdf_time_to_qpdf_time(parameter)) { usage(std::string(parameter) + " is not a valid PDF timestamp"); } - this->att.creationdate = parameter; + att.creationdate = parameter; return this; } @@ -908,7 +908,7 @@ QPDFJob::AttConfig::moddate(std::string const& parameter) if (!QUtil::pdf_time_to_qpdf_time(parameter)) { usage(std::string(parameter) + " is not a valid PDF timestamp"); } - this->att.moddate = parameter; + att.moddate = parameter; return this; } @@ -918,21 +918,21 @@ QPDFJob::AttConfig::mimetype(std::string const& parameter) if (parameter.find('/') == std::string::npos) { usage("mime type should be specified as type/subtype"); } - this->att.mimetype = parameter; + att.mimetype = parameter; return this; } QPDFJob::AttConfig* QPDFJob::AttConfig::description(std::string const& parameter) { - this->att.description = parameter; + att.description = parameter; return this; } QPDFJob::AttConfig* QPDFJob::AttConfig::replace() { - this->att.replace = true; + att.replace = true; return this; } @@ -940,28 +940,28 @@ QPDFJob::Config* QPDFJob::AttConfig::endAddAttachment() { static std::string now = QUtil::qpdf_time_to_pdf_time(QUtil::get_current_qpdf_time()); - if (this->att.path.empty()) { + if (att.path.empty()) { usage("add attachment: no file specified"); } - std::string last_element = QUtil::path_basename(this->att.path); + std::string last_element = QUtil::path_basename(att.path); if (last_element.empty()) { usage("file for --add-attachment may not be empty"); } - if (this->att.filename.empty()) { - this->att.filename = last_element; + if (att.filename.empty()) { + att.filename = last_element; } - if (this->att.key.empty()) { - this->att.key = last_element; + if (att.key.empty()) { + att.key = last_element; } - if (this->att.creationdate.empty()) { - this->att.creationdate = now; + if (att.creationdate.empty()) { + att.creationdate = now; } - if (this->att.moddate.empty()) { - this->att.moddate = now; + if (att.moddate.empty()) { + att.moddate = now; } - this->config->o.m->attachments_to_add.push_back(this->att); - return this->config; + config->o.m->attachments_to_add.push_back(att); + return config; } QPDFJob::PagesConfig::PagesConfig(Config* c) : @@ -985,21 +985,21 @@ QPDFJob::PagesConfig::endPages() if (n_specs == 0) { usage("--pages: no page specifications given"); } - return this->config; + return config; } QPDFJob::PagesConfig* QPDFJob::PagesConfig::pageSpec( std::string const& filename, std::string const& range, char const* password) { - this->config->o.m->page_specs.emplace_back(filename, password, range); + config->o.m->page_specs.emplace_back(filename, password, range); return this; } QPDFJob::PagesConfig* QPDFJob::PagesConfig::file(std::string const& arg) { - this->config->o.m->page_specs.emplace_back(arg, nullptr, ""); + config->o.m->page_specs.emplace_back(arg, "", ""); return this; } @@ -1027,11 +1027,11 @@ QPDFJob::PagesConfig::password(std::string const& arg) usage("in --pages, --password must follow a file name"); } auto& last = config->o.m->page_specs.back(); - if (last.password) { + if (!last.password.empty()) { QTC::TC("qpdf", "QPDFJob duplicated pages password"); usage("--password already specified for this file"); } - last.password = QUtil::make_shared_cstr(arg); + last.password = arg; return this; } @@ -1063,7 +1063,7 @@ QPDFJob::UOConfig::endUnderlayOverlay() usage(config->o.m->under_overlay->which + " file not specified"); } config->o.m->under_overlay = nullptr; - return this->config; + return config; } QPDFJob::UOConfig* @@ -1108,7 +1108,7 @@ QPDFJob::UOConfig::repeat(std::string const& parameter) QPDFJob::UOConfig* QPDFJob::UOConfig::password(std::string const& parameter) { - config->o.m->under_overlay->password = QUtil::make_shared_cstr(parameter); + config->o.m->under_overlay->password = parameter; return this; } @@ -1192,7 +1192,7 @@ QPDFJob::EncConfig::endEncrypt() config->o.m->encrypt = true; config->o.m->decrypt = false; config->o.m->copy_encryption = false; - return this->config; + return config; } QPDFJob::EncConfig* @@ -1341,5 +1341,5 @@ QPDFJob::PageLabelsConfig::PageLabelsConfig(Config* c) : QPDFJob::Config* QPDFJob::PageLabelsConfig::endSetPageLabels() { - return this->config; + return config; } diff --git a/libqpdf/QPDFJob_json.cc b/libqpdf/QPDFJob_json.cc index eb24bd3..c4333d0 100644 --- a/libqpdf/QPDFJob_json.cc +++ b/libqpdf/QPDFJob_json.cc @@ -630,7 +630,7 @@ QPDFJob::initializeFromJson(std::string const& json, bool partial) std::ostringstream msg; msg << m->message_prefix << ": job json has errors:"; for (auto const& error: errors) { - msg << std::endl << " " << error; + msg << "\n " << error; } throw std::runtime_error(msg.str()); } diff --git a/libqpdf/QPDFObjectHandle.cc b/libqpdf/QPDFObjectHandle.cc index 9ce200e..f0baa22 100644 --- a/libqpdf/QPDFObjectHandle.cc +++ b/libqpdf/QPDFObjectHandle.cc @@ -467,7 +467,7 @@ BaseHandle::write_json(int json_version, JSON::Writer& p) const case ::ot_real: { auto const& val = std::get(obj->value).val; - if (val.length() == 0) { + if (val.empty()) { // Can't really happen... p << "0"; } else if (val.at(0) == '.') { @@ -1184,7 +1184,7 @@ QPDFObjectHandle::mergeResources( initialized_maps = true; } auto rval_og = rval.getObjGen(); - if (rval.isIndirect() && og_to_name.count(rval_og)) { + if (rval.isIndirect() && og_to_name.contains(rval_og)) { QTC::TC("qpdf", "QPDFObjectHandle merge reuse"); auto new_key = og_to_name[rval_og]; if (new_key != key) { @@ -1208,7 +1208,7 @@ QPDFObjectHandle::mergeResources( } for (auto other_item: other_val.aitems()) { if (other_item.isScalar()) { - if (scalars.count(other_item.unparse()) == 0) { + if (!scalars.contains(other_item.unparse())) { QTC::TC("qpdf", "QPDFObjectHandle merge array"); this_val.appendItem(other_item); } else { @@ -1247,7 +1247,7 @@ QPDFObjectHandle::getUniqueResourceName( int max_suffix = min_suffix + QIntC::to_int(names.size()); while (min_suffix <= max_suffix) { std::string candidate = prefix + std::to_string(min_suffix); - if (names.count(candidate) == 0) { + if (!names.contains(candidate)) { return candidate; } // Increment after return; min_suffix should be the value diff --git a/libqpdf/QPDFOutlineDocumentHelper.cc b/libqpdf/QPDFOutlineDocumentHelper.cc index 9028cd3..13107c3 100644 --- a/libqpdf/QPDFOutlineDocumentHelper.cc +++ b/libqpdf/QPDFOutlineDocumentHelper.cc @@ -56,7 +56,7 @@ QPDFOutlineDocumentHelper::getOutlinesForPage(QPDFObjGen og) initializeByPage(); } std::vector result; - if (m->by_page.count(og)) { + if (m->by_page.contains(og)) { result = m->by_page[og]; } return result; diff --git a/libqpdf/QPDFPageObjectHelper.cc b/libqpdf/QPDFPageObjectHelper.cc index ea866f1..67badaa 100644 --- a/libqpdf/QPDFPageObjectHelper.cc +++ b/libqpdf/QPDFPageObjectHelper.cc @@ -593,7 +593,7 @@ QPDFPageObjectHelper::removeUnreferencedResourcesHelper( for (auto const& i1: to_filter) { for (auto const& n_iter: names_by_rtype[i1]) { std::string const& name = n_iter.first; - if (!known_names.count(name)) { + if (!known_names.contains(name)) { unresolved.insert(name); local_unresolved.insert(name); } @@ -624,10 +624,10 @@ QPDFPageObjectHelper::removeUnreferencedResourcesHelper( for (auto& dict: rdicts) { for (auto const& key: dict.getKeys()) { - if (is_page && unresolved.count(key)) { + if (is_page && unresolved.contains(key)) { // This name is referenced by some nested form xobject, so don't remove it. QTC::TC("qpdf", "QPDFPageObjectHelper resolving unresolved"); - } else if (!rf.getNames().count(key)) { + } else if (!rf.getNames().contains(key)) { dict.removeKey(key); } } diff --git a/libqpdf/QPDFParser.cc b/libqpdf/QPDFParser.cc index 1690f39..faeba7e 100644 --- a/libqpdf/QPDFParser.cc +++ b/libqpdf/QPDFParser.cc @@ -354,9 +354,9 @@ QPDFParser::parseRemainder(bool content_stream) fixMissingKeys(); } - if (!frame->contents_string.empty() && dict.count("/Type") && - dict["/Type"].isNameAndEquals("/Sig") && dict.count("/ByteRange") && - dict.count("/Contents") && dict["/Contents"].isString()) { + if (!frame->contents_string.empty() && dict.contains("/Type") && + dict["/Type"].isNameAndEquals("/Sig") && dict.contains("/ByteRange") && + dict.contains("/Contents") && dict["/Contents"].isString()) { dict["/Contents"] = QPDFObjectHandle::newString(frame->contents_string); dict["/Contents"].setParsedOffset(frame->contents_offset); } @@ -560,7 +560,7 @@ QPDFParser::fixMissingKeys() for (auto const& item: frame->olist) { while (true) { const std::string key = "/QPDFFake" + std::to_string(next_fake_key++); - const bool found_fake = frame->dict.count(key) == 0 && names.count(key) == 0; + const bool found_fake = !frame->dict.contains(key) && !names.contains(key); QTC::TC("qpdf", "QPDFParser found fake", (found_fake ? 0 : 1)); if (found_fake) { warn( diff --git a/libqpdf/QPDFWriter.cc b/libqpdf/QPDFWriter.cc index d18bb32..bfe0ab7 100644 --- a/libqpdf/QPDFWriter.cc +++ b/libqpdf/QPDFWriter.cc @@ -271,7 +271,7 @@ void QPDFWriter::setExtraHeaderText(std::string const& text) { m->extra_header_text = text; - if ((m->extra_header_text.length() > 0) && (*(m->extra_header_text.rbegin()) != '\n')) { + if (!m->extra_header_text.empty() && *m->extra_header_text.rbegin() != '\n') { QTC::TC("qpdf", "QPDFWriter extra header text add newline"); m->extra_header_text += "\n"; } else { @@ -1065,7 +1065,7 @@ void QPDFWriter::assignCompressedObjectNumbers(QPDFObjGen og) { int objid = og.getObj(); - if ((og.getGen() != 0) || (m->object_stream_to_objects.count(objid) == 0)) { + if ((og.getGen() != 0) || (!m->object_stream_to_objects.contains(objid))) { // This is not an object stream. return; } @@ -1115,7 +1115,7 @@ QPDFWriter::enqueueObject(QPDFObjectHandle object) m->object_queue.push_back(object); obj.renumber = m->next_objid++; - if ((og.getGen() == 0) && m->object_stream_to_objects.count(og.getObj())) { + if ((og.getGen() == 0) && m->object_stream_to_objects.contains(og.getObj())) { // For linearized files, uncompressed objects go at end, and we take care of // assigning numbers to them elsewhere. if (!m->linearized) { @@ -1285,7 +1285,7 @@ QPDFWriter::willFilterStream( filter = true; compress_stream = false; uncompress = true; - } else if (filter_on_write && m->normalize_content && m->normalized_streams.count(old_og)) { + } else if (filter_on_write && m->normalize_content && m->normalized_streams.contains(old_og)) { normalize = true; filter = true; } else if (filter_on_write && filter && m->compress_streams) { @@ -1415,11 +1415,11 @@ QPDFWriter::unparseObject( if (extensions) { std::set keys = extensions.getKeys(); - if (keys.count("/ADBE") > 0) { + if (keys.contains("/ADBE")) { have_extensions_adbe = true; keys.erase("/ADBE"); } - if (keys.size() > 0) { + if (!keys.empty()) { have_extensions_other = true; } } @@ -1807,12 +1807,12 @@ QPDFWriter::writeObject(QPDFObjectHandle object, int object_stream_index) indicateProgress(false, false); auto new_id = m->obj[old_og].renumber; if (m->qdf_mode) { - if (m->page_object_to_seq.count(old_og)) { + if (m->page_object_to_seq.contains(old_og)) { writeString("%% Page "); writeString(std::to_string(m->page_object_to_seq[old_og])); writeString("\n"); } - if (m->contents_to_page_seq.count(old_og)) { + if (m->contents_to_page_seq.contains(old_og)) { writeString("%% Contents for page "); writeString(std::to_string(m->contents_to_page_seq[old_og])); writeString("\n"); @@ -2285,7 +2285,7 @@ QPDFWriter::write() QPDFObjGen QPDFWriter::getRenumberedObjGen(QPDFObjGen og) { - return QPDFObjGen(m->obj[og].renumber, 0); + return {m->obj[og].renumber, 0}; } std::map diff --git a/libqpdf/QPDF_Dictionary.cc b/libqpdf/QPDF_Dictionary.cc index e28d30a..d34d309 100644 --- a/libqpdf/QPDF_Dictionary.cc +++ b/libqpdf/QPDF_Dictionary.cc @@ -20,7 +20,7 @@ bool BaseDictionary::hasKey(std::string const& key) const { auto d = dict(); - return d->items.count(key) > 0 && !d->items[key].isNull(); + return d->items.contains(key) && !d->items[key].null(); } QPDFObjectHandle diff --git a/libqpdf/QPDF_encryption.cc b/libqpdf/QPDF_encryption.cc index f008dfe..ccb3cd2 100644 --- a/libqpdf/QPDF_encryption.cc +++ b/libqpdf/QPDF_encryption.cc @@ -702,17 +702,17 @@ QPDF::interpretCF(std::shared_ptr encp, QPDFObjectHandle c { if (cf.isName()) { std::string filter = cf.getName(); - if (encp->crypt_filters.count(filter) != 0) { - return encp->crypt_filters[filter]; - } else if (filter == "/Identity") { + auto it = encp->crypt_filters.find(filter); + if (it != encp->crypt_filters.end()) { + return it->second; + } + if (filter == "/Identity") { return e_none; - } else { - return e_unknown; } - } else { - // Default: /Identity - return e_none; + return e_unknown; } + // Default: /Identity + return e_none; } void diff --git a/libqpdf/QPDF_json.cc b/libqpdf/QPDF_json.cc index 81c5506..a820f7b 100644 --- a/libqpdf/QPDF_json.cc +++ b/libqpdf/QPDF_json.cc @@ -161,7 +161,7 @@ QPDF::test_json_validators() auto check_fn = [&passed](char const* msg, bool expr) { if (!expr) { passed = false; - std::cerr << msg << std::endl; + std::cerr << msg << '\n'; } }; #define check(expr) check_fn(#expr, expr) @@ -192,7 +192,7 @@ QPDF::test_json_validators() check(is_unicode_string("u:potato", str)); check(str == "potato"); check(is_unicode_string("u:", str)); - check(str == ""); + check(str.empty()); check(!is_binary_string("", str)); check(!is_binary_string("x:", str)); check(!is_binary_string("b:1", str)); @@ -889,7 +889,7 @@ QPDF::writeJSON( for (auto& obj: getAllObjects()) { auto const og = obj.getObjGen(); std::string key = "obj:" + og.unparse(' ') + " R"; - if (all_objects || wanted_objects.count(key)) { + if (all_objects || wanted_objects.contains(key)) { if (first) { jw << "\n \"" << key; first = false; @@ -911,7 +911,7 @@ QPDF::writeJSON( } } } - if (all_objects || wanted_objects.count("trailer")) { + if (all_objects || wanted_objects.contains("trailer")) { if (!first) { jw << "\n },"; } diff --git a/libqpdf/QPDF_linearization.cc b/libqpdf/QPDF_linearization.cc index 6519f6d..c9f0233 100644 --- a/libqpdf/QPDF_linearization.cc +++ b/libqpdf/QPDF_linearization.cc @@ -10,7 +10,7 @@ #include #include #include -#include +#include #include #include #include @@ -502,7 +502,7 @@ QPDF::checkLinearizationInternal() qpdf_offset_t max_E = -1; for (auto const& oh: m->part6) { QPDFObjGen og(oh.getObjGen()); - if (m->obj_cache.count(og) == 0) { + if (!m->obj_cache.contains(og)) { // All objects have to have been dereferenced to be classified. throw std::logic_error("linearization part6 object not in cache"); } @@ -530,12 +530,12 @@ QPDF::checkLinearizationInternal() qpdf_offset_t QPDF::maxEnd(ObjUser const& ou) { - if (m->obj_user_to_objects.count(ou) == 0) { + if (!m->obj_user_to_objects.contains(ou)) { stopOnError("no entry in object user table for requested object user"); } qpdf_offset_t end = 0; for (auto const& og: m->obj_user_to_objects[ou]) { - if (!m->obj_cache.count(og)) { + if (!m->obj_cache.contains(og)) { stopOnError("unknown object referenced in object user table"); } end = std::max(end, m->obj_cache[og].end_after_space); @@ -568,7 +568,7 @@ QPDF::getLinearizationOffset(QPDFObjGen og) QPDFObjectHandle QPDF::getUncompressedObject(QPDFObjectHandle& obj, std::map const& object_stream_data) { - if (obj.isNull() || (object_stream_data.count(obj.getObjectID()) == 0)) { + if (obj.null() || (!object_stream_data.contains(obj.getObjectID()))) { return obj; } else { int repl = (*(object_stream_data.find(obj.getObjectID()))).second; @@ -593,11 +593,11 @@ QPDF::lengthNextN(int first_object, int n) int length = 0; for (int i = 0; i < n; ++i) { QPDFObjGen og(first_object + i, 0); - if (m->xref_table.count(og) == 0) { + if (!m->xref_table.contains(og)) { linearizationWarning( "no xref table entry for " + std::to_string(first_object + i) + " 0"); } else { - if (m->obj_cache.count(og) == 0) { + if (!m->obj_cache.contains(og)) { stopOnError("found unknown object while calculating length for linearization data"); } length += toI(m->obj_cache[og].end_after_space - getLinearizationOffset(og)); @@ -625,7 +625,7 @@ QPDF::checkHPageOffset( int npages = toI(pages.size()); qpdf_offset_t table_offset = adjusted_offset(m->page_offset_hints.first_page_offset); QPDFObjGen first_page_og(pages.at(0).getObjGen()); - if (m->xref_table.count(first_page_og) == 0) { + if (!m->xref_table.contains(first_page_og)) { stopOnError("supposed first page object is not known"); } qpdf_offset_t offset = getLinearizationOffset(first_page_og); @@ -636,7 +636,7 @@ QPDF::checkHPageOffset( for (int pageno = 0; pageno < npages; ++pageno) { QPDFObjGen page_og(pages.at(toS(pageno)).getObjGen()); int first_object = page_og.getObj(); - if (m->xref_table.count(page_og) == 0) { + if (!m->xref_table.contains(page_og)) { stopOnError("unknown object in page offset hint table"); } offset = getLinearizationOffset(page_og); @@ -677,7 +677,7 @@ QPDF::checkHPageOffset( for (size_t i = 0; i < toS(he.nshared_objects); ++i) { int idx = he.shared_identifiers.at(i); - if (shared_idx_to_obj.count(idx) == 0) { + if (!shared_idx_to_obj.contains(idx)) { stopOnError("unable to get object for item in shared objects hint table"); } hint_shared.insert(shared_idx_to_obj[idx]); @@ -693,7 +693,7 @@ QPDF::checkHPageOffset( } for (int iter: hint_shared) { - if (!computed_shared.count(iter)) { + if (!computed_shared.contains(iter)) { // pdlin puts thumbnails here even though it shouldn't linearizationWarning( "page " + std::to_string(pageno) + ": shared object " + std::to_string(iter) + @@ -702,7 +702,7 @@ QPDF::checkHPageOffset( } for (int iter: computed_shared) { - if (!hint_shared.count(iter)) { + if (!hint_shared.contains(iter)) { // Acrobat does not put some things including at least built-in fonts and procsets // here, at least in some cases. linearizationWarning( @@ -755,7 +755,7 @@ QPDF::checkHSharedObject(std::vector const& pages, std::mapxref_table.count(og) == 0) { + if (!m->xref_table.contains(og)) { stopOnError("unknown object in shared object hint table"); } qpdf_offset_t offset = getLinearizationOffset(og); @@ -806,7 +806,7 @@ QPDF::checkHOutlines() return; } QPDFObjGen og(outlines.getObjGen()); - if (m->xref_table.count(og) == 0) { + if (!m->xref_table.contains(og)) { stopOnError("unknown object in outlines hint table"); } qpdf_offset_t offset = getLinearizationOffset(og); @@ -1086,7 +1086,7 @@ QPDF::calculateLinearizationData(T const& object_stream_data) break; case ObjUser::ou_root_key: - if (open_document_keys.count(ou.key) > 0) { + if (open_document_keys.contains(ou.key)) { in_open_document = true; } else if (ou.key == "/Outlines") { in_outlines = true; @@ -1187,7 +1187,7 @@ QPDF::calculateLinearizationData(T const& object_stream_data) stopOnError("no pages found while calculating linearization data"); } QPDFObjGen first_page_og(pages.at(0).getObjGen()); - if (!lc_first_page_private.count(first_page_og)) { + if (!lc_first_page_private.contains(first_page_og)) { stopOnError( "INTERNAL ERROR: QPDF::calculateLinearizationData: first page " "object not in lc_first_page_private"); @@ -1226,7 +1226,7 @@ QPDF::calculateLinearizationData(T const& object_stream_data) // Place this page's page object QPDFObjGen page_og(pages.at(i).getObjGen()); - if (!lc_other_page_private.count(page_og)) { + if (!lc_other_page_private.contains(page_og)) { stopOnError( "INTERNAL ERROR: QPDF::calculateLinearizationData: page object for page " + std::to_string(i) + " not in lc_other_page_private"); @@ -1240,11 +1240,11 @@ QPDF::calculateLinearizationData(T const& object_stream_data) m->c_page_offset_data.entries.at(i).nobjects = 1; ObjUser ou(ObjUser::ou_page, toI(i)); - if (m->obj_user_to_objects.count(ou) == 0) { + if (!m->obj_user_to_objects.contains(ou)) { stopOnError("found unreferenced page while calculating linearization data"); } for (auto const& og: m->obj_user_to_objects[ou]) { - if (lc_other_page_private.count(og)) { + if (lc_other_page_private.contains(og)) { lc_other_page_private.erase(og); m->part7.push_back(getObject(og)); ++m->c_page_offset_data.entries.at(i).nobjects; @@ -1279,7 +1279,7 @@ QPDF::calculateLinearizationData(T const& object_stream_data) stopOnError("found empty pages tree while calculating linearization data"); } for (auto const& og: pages_ogs) { - if (lc_other.count(og)) { + if (lc_other.contains(og)) { lc_other.erase(og); m->part9.push_back(getObject(og)); } @@ -1293,7 +1293,7 @@ QPDF::calculateLinearizationData(T const& object_stream_data) if (!thumb.isNull()) { // Output the thumbnail itself QPDFObjGen thumb_og(thumb.getObjGen()); - if (lc_thumbnail_private.count(thumb_og)) { + if (lc_thumbnail_private.contains(thumb_og)) { lc_thumbnail_private.erase(thumb_og); m->part9.push_back(thumb); } else { @@ -1304,7 +1304,7 @@ QPDF::calculateLinearizationData(T const& object_stream_data) } std::set& ogs = m->obj_user_to_objects[ObjUser(ObjUser::ou_thumb, toI(i))]; for (auto const& og: ogs) { - if (lc_thumbnail_private.count(og)) { + if (lc_thumbnail_private.contains(og)) { lc_thumbnail_private.erase(og); m->part9.push_back(getObject(og)); } @@ -1384,11 +1384,11 @@ QPDF::calculateLinearizationData(T const& object_stream_data) for (size_t i = 1; i < toS(npages); ++i) { CHPageOffsetEntry& pe = m->c_page_offset_data.entries.at(i); ObjUser ou(ObjUser::ou_page, toI(i)); - if (m->obj_user_to_objects.count(ou) == 0) { + if (!m->obj_user_to_objects.contains(ou)) { stopOnError("found unreferenced page while calculating linearization data"); } for (auto const& og: m->obj_user_to_objects[ou]) { - if ((m->object_to_obj_users[og].size() > 1) && (obj_to_index.count(og.getObj()) > 0)) { + if ((m->object_to_obj_users[og].size() > 1) && (obj_to_index.contains(og.getObj()))) { int idx = obj_to_index[og.getObj()]; ++pe.nshared_objects; pe.shared_identifiers.push_back(idx); diff --git a/libqpdf/QPDF_objects.cc b/libqpdf/QPDF_objects.cc index 7ef8427..9d02e67 100644 --- a/libqpdf/QPDF_objects.cc +++ b/libqpdf/QPDF_objects.cc @@ -153,7 +153,7 @@ QPDF::parse(char const* password) initializeEncryption(); m->parsed = true; - if (m->xref_table.size() > 0 && !getRoot().getKey("/Pages").isDictionary()) { + if (!m->xref_table.empty() && !getRoot().getKey("/Pages").isDictionary()) { // QPDFs created from JSON have an empty xref table and no root object yet. throw damagedPDF("", -1, "unable to find page tree"); } @@ -442,7 +442,7 @@ QPDF::read_xref(qpdf_offset_t xref_offset, bool in_stream_recovery) } else { xref_offset = read_xrefStream(xref_offset, in_stream_recovery); } - if (visited.count(xref_offset) != 0) { + if (visited.contains(xref_offset)) { QTC::TC("qpdf", "QPDF xref loop"); throw damagedPDF("", -1, "loop detected following xref tables"); } @@ -1020,7 +1020,7 @@ QPDF::insertXrefEntry(int obj, int f0, qpdf_offset_t f1, int f2) return; } - if (m->deleted_objects.count(obj)) { + if (m->deleted_objects.contains(obj)) { QTC::TC("qpdf", "QPDF xref deleted object"); return; } @@ -1056,7 +1056,7 @@ QPDF::insertXrefEntry(int obj, int f0, qpdf_offset_t f1, int f2) void QPDF::insertFreeXrefEntry(QPDFObjGen og) { - if (!m->xref_table.count(og)) { + if (!m->xref_table.contains(og)) { m->deleted_objects.insert(og.getObj()); } } @@ -1476,7 +1476,7 @@ QPDF::readObjectAtOffset( if (try_recovery) { // Try again after reconstructing xref table reconstruct_xref(e); - if (m->xref_table.count(exp_og) && (m->xref_table[exp_og].getType() == 1)) { + if (m->xref_table.contains(exp_og) && m->xref_table[exp_og].getType() == 1) { qpdf_offset_t new_offset = m->xref_table[exp_og].getOffset(); QPDFObjectHandle result = readObjectAtOffset(false, new_offset, description, exp_og, og, false); @@ -1522,7 +1522,7 @@ QPDF::readObjectAtOffset( } } qpdf_offset_t end_after_space = m->file->tell(); - if (skip_cache_if_in_xref && m->xref_table.count(og)) { + if (skip_cache_if_in_xref && m->xref_table.contains(og)) { // Ordinarily, an object gets read here when resolved through xref table or stream. In // the special case of the xref stream and linearization hint tables, the offset comes // from another source. For the specific case of xref streams, the xref stream is read @@ -1564,7 +1564,7 @@ QPDF::resolve(QPDFObjGen og) return m->obj_cache[og].object; } - if (m->resolving.count(og)) { + if (m->resolving.contains(og)) { // This can happen if an object references itself directly or indirectly in some key that // has to be resolved during object parsing, such as stream length. QTC::TC("qpdf", "QPDF recursion loop in resolve"); @@ -1574,7 +1574,7 @@ QPDF::resolve(QPDFObjGen og) } ResolveRecorder rr(this, og); - if (m->xref_table.count(og) != 0) { + if (m->xref_table.contains(og)) { QPDFXRefEntry const& entry = m->xref_table[og]; try { switch (entry.getType()) { @@ -1628,7 +1628,7 @@ QPDF::resolveObjectsInStream(int obj_stream_number) true}; }; - if (m->resolved_object_streams.count(obj_stream_number)) { + if (m->resolved_object_streams.contains(obj_stream_number)) { return; } m->resolved_object_streams.insert(obj_stream_number); @@ -1791,7 +1791,7 @@ QPDF::updateCache( bool QPDF::isCached(QPDFObjGen og) { - return m->obj_cache.count(og) != 0; + return m->obj_cache.contains(og); } bool @@ -1807,7 +1807,7 @@ QPDF::nextObjGen() if (max_objid == std::numeric_limits::max()) { throw std::range_error("max object id is too high to create new objects"); } - return QPDFObjGen(max_objid + 1, 0); + return {max_objid + 1, 0}; } QPDFObjectHandle @@ -1835,7 +1835,7 @@ QPDF::getObjectForParser(int id, int gen, bool parse_pdf) if (auto iter = m->obj_cache.find(og); iter != m->obj_cache.end()) { return iter->second.object; } - if (m->xref_table.count(og) || !m->parsed) { + if (m->xref_table.contains(og) || !m->parsed) { return m->obj_cache.insert({og, QPDFObject::create(this, og)}) .first->second.object; } @@ -1852,7 +1852,7 @@ QPDF::getObjectForJSON(int id, int gen) auto [it, inserted] = m->obj_cache.try_emplace(og); auto& obj = it->second.object; if (inserted) { - obj = (m->parsed && !m->xref_table.count(og)) + obj = (m->parsed && !m->xref_table.contains(og)) ? QPDFObject::create(this, og) : QPDFObject::create(this, og); } @@ -1864,7 +1864,7 @@ QPDF::getObject(QPDFObjGen og) { if (auto it = m->obj_cache.find(og); it != m->obj_cache.end()) { return {it->second.object}; - } else if (m->parsed && !m->xref_table.count(og)) { + } else if (m->parsed && !m->xref_table.contains(og)) { return QPDFObject::create(); } else { auto result = @@ -1932,8 +1932,8 @@ QPDF::tableSize() { // If obj_cache is dense, accommodate all object in tables,else accommodate only original // objects. - auto max_xref = m->xref_table.size() ? m->xref_table.crbegin()->first.getObj() : 0; - auto max_obj = m->obj_cache.size() ? m->obj_cache.crbegin()->first.getObj() : 0; + auto max_xref = !m->xref_table.empty() ? m->xref_table.crbegin()->first.getObj() : 0; + auto max_obj = !m->obj_cache.empty() ? m->obj_cache.crbegin()->first.getObj() : 0; auto max_id = std::numeric_limits::max() - 1; if (max_obj >= max_id || max_xref >= max_id) { // Temporary fix. Long-term solution is diff --git a/libqpdf/QPDF_pages.cc b/libqpdf/QPDF_pages.cc index f19539a..1b18981 100644 --- a/libqpdf/QPDF_pages.cc +++ b/libqpdf/QPDF_pages.cc @@ -303,7 +303,7 @@ QPDF::insertPage(QPDFObjectHandle newpage, int pos) : 2); // insert in middle auto og = newpage.getObjGen(); - if (m->pageobj_to_pages_pos.count(og)) { + if (m->pageobj_to_pages_pos.contains(og)) { QTC::TC("qpdf", "QPDF resolve duplicated page in insert"); newpage = makeIndirectObject(QPDFObjectHandle(newpage).shallowCopy()); } diff --git a/libqpdf/QTC.cc b/libqpdf/QTC.cc index ae9649a..e69f2b7 100644 --- a/libqpdf/QTC.cc +++ b/libqpdf/QTC.cc @@ -39,7 +39,7 @@ QTC::TC_real(char const* const scope, char const* const ccase, int n) } #undef TC_ENV - if (cache.count(std::make_pair(ccase, n))) { + if (cache.contains(std::make_pair(ccase, n))) { return; } cache.insert(std::make_pair(ccase, n)); diff --git a/libqpdf/QUtil.cc b/libqpdf/QUtil.cc index 05b53ba..19e85b4 100644 --- a/libqpdf/QUtil.cc +++ b/libqpdf/QUtil.cc @@ -1395,7 +1395,7 @@ QUtil::parse_numrange(char const* range, int max) work = last_group; last_group.clear(); for (auto n: work) { - if (exclusions.count(n) == 0) { + if (!exclusions.contains(n)) { last_group.emplace_back(n); } } @@ -1886,7 +1886,7 @@ QUtil::possible_repaired_encodings(std::string supplied) std::vector t; std::set seen; for (auto const& iter: result) { - if (!seen.count(iter)) { + if (!seen.contains(iter)) { seen.insert(iter); t.push_back(iter); } @@ -1988,7 +1988,7 @@ QUtil::get_max_memory_usage() attrs[m2->str(1)] = m2->str(2); } if (tag == "total") { - if (attrs.count("size") > 0) { + if (attrs.contains("size")) { result += QIntC::to_size(QUtil::string_to_ull(attrs["size"].c_str())); } } else if (tag == "system" && attrs["type"] == "max") { diff --git a/libqpdf/ResourceFinder.cc b/libqpdf/ResourceFinder.cc index 798fe67..06d37e1 100644 --- a/libqpdf/ResourceFinder.cc +++ b/libqpdf/ResourceFinder.cc @@ -1,10 +1,5 @@ #include -ResourceFinder::ResourceFinder() : - last_name_offset(0) -{ -} - void ResourceFinder::handleObject(QPDFObjectHandle obj, size_t offset, size_t) { diff --git a/libqpdf/qpdf/AES_PDF_native.hh b/libqpdf/qpdf/AES_PDF_native.hh index 0b93203..527e8cb 100644 --- a/libqpdf/qpdf/AES_PDF_native.hh +++ b/libqpdf/qpdf/AES_PDF_native.hh @@ -25,7 +25,7 @@ class AES_PDF_native unsigned char* cbc_block; std::unique_ptr key; std::unique_ptr rk; - unsigned int nrounds; + unsigned int nrounds{0}; }; #endif // AES_PDF_NATIVE_HH diff --git a/libqpdf/qpdf/BitWriter.hh b/libqpdf/qpdf/BitWriter.hh index 24c7416..9b8e2bc 100644 --- a/libqpdf/qpdf/BitWriter.hh +++ b/libqpdf/qpdf/BitWriter.hh @@ -21,8 +21,8 @@ class BitWriter private: Pipeline* pl; - unsigned char ch; - size_t bit_offset; + unsigned char ch{0}; + size_t bit_offset{7}; }; #endif // BITWRITER_HH diff --git a/libqpdf/qpdf/ContentNormalizer.hh b/libqpdf/qpdf/ContentNormalizer.hh index 930cf14..7c3b6d2 100644 --- a/libqpdf/qpdf/ContentNormalizer.hh +++ b/libqpdf/qpdf/ContentNormalizer.hh @@ -6,7 +6,7 @@ class ContentNormalizer final: public QPDFObjectHandle::TokenFilter { public: - ContentNormalizer(); + ContentNormalizer() = default; ~ContentNormalizer() final = default; void handleToken(QPDFTokenizer::Token const&) final; @@ -22,8 +22,8 @@ class ContentNormalizer final: public QPDFObjectHandle::TokenFilter } private: - bool any_bad_tokens; - bool last_token_was_bad; + bool any_bad_tokens{false}; + bool last_token_was_bad{false}; }; #endif // CONTENTNORMALIZER_HH diff --git a/libqpdf/qpdf/InsecureRandomDataProvider.hh b/libqpdf/qpdf/InsecureRandomDataProvider.hh index bab4e00..b9870d1 100644 --- a/libqpdf/qpdf/InsecureRandomDataProvider.hh +++ b/libqpdf/qpdf/InsecureRandomDataProvider.hh @@ -3,18 +3,18 @@ #include -class InsecureRandomDataProvider: public RandomDataProvider +class InsecureRandomDataProvider final: public RandomDataProvider { public: - InsecureRandomDataProvider(); - ~InsecureRandomDataProvider() override = default; - void provideRandomData(unsigned char* data, size_t len) override; + InsecureRandomDataProvider() = default; + ~InsecureRandomDataProvider() final = default; + void provideRandomData(unsigned char* data, size_t len) final; static RandomDataProvider* getInstance(); private: long random(); - bool seeded_random; + bool seeded_random{false}; }; #endif // INSECURERANDOMDATAPROVIDER_HH diff --git a/libqpdf/qpdf/NNTree.hh b/libqpdf/qpdf/NNTree.hh index 4b5ba20..e62e959 100644 --- a/libqpdf/qpdf/NNTree.hh +++ b/libqpdf/qpdf/NNTree.hh @@ -84,7 +84,7 @@ class NNTreeIterator NNTreeImpl& impl; std::list path; QPDFObjectHandle node; - int item_number; + int item_number{-1}; value_type ivalue; }; @@ -123,7 +123,7 @@ class NNTreeImpl NNTreeDetails const& details; QPDF& qpdf; - int split_threshold; + int split_threshold{32}; QPDFObjectHandle oh; bool auto_repair; }; diff --git a/libqpdf/qpdf/Pl_SHA2.hh b/libqpdf/qpdf/Pl_SHA2.hh index ee4c5c1..e3d924b 100644 --- a/libqpdf/qpdf/Pl_SHA2.hh +++ b/libqpdf/qpdf/Pl_SHA2.hh @@ -25,7 +25,7 @@ class Pl_SHA2 final: public Pipeline std::string getRawDigest(); private: - bool in_progress; + bool in_progress{false}; std::shared_ptr crypto; }; diff --git a/libqpdf/qpdf/QPDFArgParser.hh b/libqpdf/qpdf/QPDFArgParser.hh index ed161d5..7e4c92e 100644 --- a/libqpdf/qpdf/QPDFArgParser.hh +++ b/libqpdf/qpdf/QPDFArgParser.hh @@ -206,9 +206,9 @@ class QPDFArgParser char const* const* argv; std::string whoami; std::string progname_env; - int cur_arg; - bool bash_completion; - bool zsh_completion; + int cur_arg{0}; + bool bash_completion{false}; + bool zsh_completion{false}; std::string bash_prev; std::string bash_cur; std::string bash_line; @@ -216,13 +216,13 @@ class QPDFArgParser std::map option_tables; option_table_t main_option_table; option_table_t help_option_table; - option_table_t* option_table; + option_table_t* option_table{nullptr}; std::string option_table_name; - bare_arg_handler_t final_check_handler; - std::vector> new_argv; - std::vector> bash_argv; - std::shared_ptr argv_ph; - std::shared_ptr bash_argv_ph; + bare_arg_handler_t final_check_handler{nullptr}; + std::vector new_argv; + std::vector bash_argv; + std::vector argv_ph; + std::vector bash_argv_ph; std::map help_topics; std::map option_help; std::string help_footer; diff --git a/libqpdf/qpdf/QPDFCrypto_native.hh b/libqpdf/qpdf/QPDFCrypto_native.hh index 4dd6362..0ca4b37 100644 --- a/libqpdf/qpdf/QPDFCrypto_native.hh +++ b/libqpdf/qpdf/QPDFCrypto_native.hh @@ -8,37 +8,38 @@ #include #include -class QPDFCrypto_native: public QPDFCryptoImpl +class QPDFCrypto_native final: public QPDFCryptoImpl { public: QPDFCrypto_native() = default; - virtual ~QPDFCrypto_native() = default; + ~QPDFCrypto_native() final = default; - virtual void provideRandomData(unsigned char* data, size_t len); + void provideRandomData(unsigned char* data, size_t len) final; - virtual void MD5_init(); - virtual void MD5_update(unsigned char const* data, size_t len); - virtual void MD5_finalize(); - virtual void MD5_digest(MD5_Digest); + void MD5_init() final; + void MD5_update(unsigned char const* data, size_t len) final; + void MD5_finalize() final; + void MD5_digest(MD5_Digest) final; - virtual void RC4_init(unsigned char const* key_data, int key_len = -1); - virtual void RC4_process(unsigned char const* in_data, size_t len, unsigned char* out_data = 0); - virtual void RC4_finalize(); + void RC4_init(unsigned char const* key_data, int key_len = -1) final; + void + RC4_process(unsigned char const* in_data, size_t len, unsigned char* out_data = nullptr) final; + void RC4_finalize() final; - virtual void SHA2_init(int bits); - virtual void SHA2_update(unsigned char const* data, size_t len); - virtual void SHA2_finalize(); - virtual std::string SHA2_digest(); + void SHA2_init(int bits) final; + void SHA2_update(unsigned char const* data, size_t len) final; + void SHA2_finalize() final; + std::string SHA2_digest() final; - virtual void rijndael_init( + void rijndael_init( bool encrypt, unsigned char const* key_data, size_t key_len, bool cbc_mode, - unsigned char* cbc_block); - virtual void rijndael_process(unsigned char* in_data, unsigned char* out_data); - virtual void rijndael_finalize(); + unsigned char* cbc_block) final; + void rijndael_process(unsigned char* in_data, unsigned char* out_data) final; + void rijndael_finalize() final; private: std::shared_ptr md5; diff --git a/libqpdf/qpdf/RC4_native.hh b/libqpdf/qpdf/RC4_native.hh index 7607c0c..67bdd03 100644 --- a/libqpdf/qpdf/RC4_native.hh +++ b/libqpdf/qpdf/RC4_native.hh @@ -10,7 +10,7 @@ class RC4_native RC4_native(unsigned char const* key_data, int key_len = -1); // out_data = 0 means to encrypt/decrypt in place - void process(unsigned char const* in_data, size_t len, unsigned char* out_data = 0); + void process(unsigned char const* in_data, size_t len, unsigned char* out_data = nullptr); private: class RC4Key diff --git a/libqpdf/qpdf/ResourceFinder.hh b/libqpdf/qpdf/ResourceFinder.hh index 1c4c59a..04614d7 100644 --- a/libqpdf/qpdf/ResourceFinder.hh +++ b/libqpdf/qpdf/ResourceFinder.hh @@ -3,20 +3,20 @@ #include -class ResourceFinder: public QPDFObjectHandle::ParserCallbacks +class ResourceFinder final: public QPDFObjectHandle::ParserCallbacks { public: - ResourceFinder(); - ~ResourceFinder() override = default; - void handleObject(QPDFObjectHandle, size_t, size_t) override; - void handleEOF() override; + ResourceFinder() = default; + ~ResourceFinder() final = default; + void handleObject(QPDFObjectHandle, size_t, size_t) final; + void handleEOF() final; std::set const& getNames() const; std::map>> const& getNamesByResourceType() const; private: std::string last_name; - size_t last_name_offset; + size_t last_name_offset{0}; std::set names; std::map>> names_by_resource_type; }; diff --git a/libtests/aes.cc b/libtests/aes.cc index 370cd65..ad1e9f8 100644 --- a/libtests/aes.cc +++ b/libtests/aes.cc @@ -11,15 +11,15 @@ static void usage() { - std::cerr << "Usage: aes options hex-key infile outfile" << std::endl - << " -cbc -- disable CBC mode" << std::endl - << " +cbc -- enable CBC mode" << std::endl - << " -encrypt -- encrypt" << std::endl - << " -decrypt -- decrypt CBC mode" << std::endl - << " -zero-iv -- use zero initialization vector" << std::endl - << " -static-iv -- use static initialization vector" << std::endl - << " -no-padding -- disable padding" << std::endl - << "Options must precede key and file names." << std::endl; + std::cerr << "Usage: aes options hex-key infile outfile" << '\n' + << " -cbc -- disable CBC mode" << '\n' + << " +cbc -- enable CBC mode" << '\n' + << " -encrypt -- encrypt" << '\n' + << " -decrypt -- decrypt CBC mode" << '\n' + << " -zero-iv -- use zero initialization vector" << '\n' + << " -static-iv -- use static initialization vector" << '\n' + << " -no-padding -- disable padding" << '\n' + << "Options must precede key and file names." << '\n'; exit(2); } diff --git a/libtests/arg_parser.cc b/libtests/arg_parser.cc index ad9d85e..872fbad 100644 --- a/libtests/arg_parser.cc +++ b/libtests/arg_parser.cc @@ -82,7 +82,7 @@ void ArgParser::output(std::string const& msg) { if (!this->ap.isCompleting()) { - std::cout << msg << std::endl; + std::cout << msg << '\n'; } } @@ -160,7 +160,7 @@ ArgParser::test_exceptions() fn(); assert(msg == nullptr); } catch (std::exception& e) { - std::cout << msg << ": " << e.what() << std::endl; + std::cout << msg << ": " << e.what() << '\n'; } }; @@ -196,10 +196,10 @@ main(int argc, char* argv[]) try { ap.parseArgs(); } catch (QPDFUsage& e) { - std::cerr << "usage: " << e.what() << std::endl; + std::cerr << "usage: " << e.what() << '\n'; exit(2); } catch (std::exception& e) { - std::cerr << "exception: " << e.what() << std::endl; + std::cerr << "exception: " << e.what() << '\n'; exit(3); } return 0; diff --git a/libtests/ascii85.cc b/libtests/ascii85.cc index dad0c30..ded081d 100644 --- a/libtests/ascii85.cc +++ b/libtests/ascii85.cc @@ -23,7 +23,7 @@ main() } decode.finish(); } catch (std::exception& e) { - std::cerr << e.what() << std::endl; + std::cerr << e.what() << '\n'; exit(2); } diff --git a/libtests/base64.cc b/libtests/base64.cc index 41dc676..f65af1b 100644 --- a/libtests/base64.cc +++ b/libtests/base64.cc @@ -20,7 +20,7 @@ write_some(FILE* f, size_t bytes, Pipeline* p) } if (len < bytes) { if (ferror(f)) { - std::cerr << "error reading file" << std::endl; + std::cerr << "error reading file" << '\n'; exit(2); } p->finish(); @@ -32,7 +32,7 @@ write_some(FILE* f, size_t bytes, Pipeline* p) static void usage() { - std::cerr << "Usage: base64 encode|decode" << std::endl; + std::cerr << "Usage: base64 encode|decode" << '\n'; exit(2); } @@ -74,7 +74,7 @@ main(int argc, char* argv[]) } } } catch (std::exception& e) { - std::cout << "exception: " << e.what() << std::endl; + std::cout << "exception: " << e.what() << '\n'; exit(2); } diff --git a/libtests/bits.cc b/libtests/bits.cc index bba1fd4..b9b5547 100644 --- a/libtests/bits.cc +++ b/libtests/bits.cc @@ -16,7 +16,7 @@ static void print_values(long long byte_offset, size_t bit_offset, size_t bits_available) { std::cout << "byte offset = " << byte_offset << ", " << "bit offset = " << bit_offset << ", " - << "bits available = " << bits_available << std::endl; + << "bits available = " << bits_available << '\n'; } static void @@ -29,7 +29,7 @@ test_read_bits( { unsigned long result = QIntC::to_ulong(read_bits(p, bit_offset, bits_available, bits_wanted)); - std::cout << "bits read: " << bits_wanted << ", result = " << result << std::endl; + std::cout << "bits read: " << bits_wanted << ", result = " << result << '\n'; print_values(p - buf, bit_offset, bits_available); } @@ -39,7 +39,7 @@ test_write_bits( { write_bits(ch, bit_offset, val, bits, bp); std::cout << "ch = " << QUtil::uint_to_string_base(ch, 16, 2) << ", bit_offset = " << bit_offset - << std::endl; + << '\n'; } static void @@ -52,7 +52,7 @@ print_buffer(Pl_Buffer* bp) for (unsigned long i = 0; i < l; ++i) { std::cout << QUtil::uint_to_string_base(p[i], 16, 2) << ((i == l - 1) ? "\n" : " "); } - std::cout << std::endl; + std::cout << '\n'; delete b; } @@ -86,12 +86,12 @@ test() try { test_read_bits(buf, p, bit_offset, bits_available, 4); } catch (std::exception& e) { - std::cout << "exception: " << e.what() << std::endl; + std::cout << "exception: " << e.what() << '\n'; print_values(p - buf, bit_offset, bits_available); } test_read_bits(buf, p, bit_offset, bits_available, 3); - std::cout << std::endl; + std::cout << '\n'; // 11110101 00010101 01100101 01111001: 00010010 10001001 01110101 01001011 @@ -101,29 +101,29 @@ test() print_values(p - buf, bit_offset, bits_available); test_read_bits(buf, p, bit_offset, bits_available, 32); test_read_bits(buf, p, bit_offset, bits_available, 32); - std::cout << std::endl; + std::cout << '\n'; BitStream b(buf, 8); - std::cout << b.getBits(32) << std::endl; + std::cout << b.getBits(32) << '\n'; b.reset(); - std::cout << b.getBits(32) << std::endl; - std::cout << b.getBits(32) << std::endl; - std::cout << std::endl; + std::cout << b.getBits(32) << '\n'; + std::cout << b.getBits(32) << '\n'; + std::cout << '\n'; b.reset(); - std::cout << b.getBits(6) << std::endl; + std::cout << b.getBits(6) << '\n'; b.skipToNextByte(); - std::cout << b.getBits(8) << std::endl; + std::cout << b.getBits(8) << '\n'; b.skipToNextByte(); - std::cout << b.getBits(8) << std::endl; - std::cout << std::endl; + std::cout << b.getBits(8) << '\n'; + std::cout << '\n'; b.reset(); - std::cout << b.getBitsSigned(3) << std::endl; - std::cout << b.getBitsSigned(6) << std::endl; - std::cout << b.getBitsSigned(5) << std::endl; - std::cout << b.getBitsSigned(1) << std::endl; - std::cout << b.getBitsSigned(17) << std::endl; - std::cout << std::endl; + std::cout << b.getBitsSigned(3) << '\n'; + std::cout << b.getBitsSigned(6) << '\n'; + std::cout << b.getBitsSigned(5) << '\n'; + std::cout << b.getBitsSigned(1) << '\n'; + std::cout << b.getBitsSigned(17) << '\n'; + std::cout << '\n'; // Write tests @@ -176,9 +176,9 @@ main() try { test(); } catch (std::exception& e) { - std::cout << "unexpected exception: " << e.what() << std::endl; + std::cout << "unexpected exception: " << e.what() << '\n'; exit(2); } - std::cout << "done" << std::endl; + std::cout << "done" << '\n'; return 0; } diff --git a/libtests/buffer.cc b/libtests/buffer.cc index 4326901..295597c 100644 --- a/libtests/buffer.cc +++ b/libtests/buffer.cc @@ -85,22 +85,22 @@ main() bp1.write(uc("12345"), 5); bp1.write(uc("67890"), 5); bp1.finish(); - std::cout << "count: " << count.getCount() << std::endl; + std::cout << "count: " << count.getCount() << '\n'; bp1.write(uc("abcde"), 5); bp1.write(uc("fghij"), 6); bp1.finish(); - std::cout << "count: " << count.getCount() << std::endl; + std::cout << "count: " << count.getCount() << '\n'; Buffer* b = bp1.getBuffer(); - std::cout << "size: " << b->getSize() << std::endl; - std::cout << "data: " << b->getBuffer() << std::endl; + std::cout << "size: " << b->getSize() << '\n'; + std::cout << "data: " << b->getBuffer() << '\n'; delete b; bp1.write(uc("qwert"), 5); bp1.write(uc("yuiop"), 6); bp1.finish(); - std::cout << "count: " << count.getCount() << std::endl; + std::cout << "count: " << count.getCount() << '\n'; b = bp1.getBuffer(); - std::cout << "size: " << b->getSize() << std::endl; - std::cout << "data: " << b->getBuffer() << std::endl; + std::cout << "size: " << b->getSize() << '\n'; + std::cout << "data: " << b->getBuffer() << '\n'; delete b; Pl_Buffer bp2("bp2"); @@ -109,12 +109,12 @@ main() try { delete bp2.getBuffer(); } catch (std::exception& e) { - std::cout << e.what() << std::endl; + std::cout << e.what() << '\n'; } bp2.finish(); b = bp2.getBuffer(); - std::cout << "size: " << b->getSize() << std::endl; - std::cout << "data: " << b->getBuffer() << std::endl; + std::cout << "size: " << b->getSize() << '\n'; + std::cout << "data: " << b->getBuffer() << '\n'; delete b; unsigned char lbuf[10]; @@ -125,17 +125,17 @@ main() Pl_Buffer bp3("bp3"); b = bp3.getBuffer(); - std::cout << "size: " << b->getSize() << std::endl; + std::cout << "size: " << b->getSize() << '\n'; delete b; // Should be able to call getBuffer again and get an empty buffer b = bp3.getBuffer(); - std::cout << "size: " << b->getSize() << std::endl; + std::cout << "size: " << b->getSize() << '\n'; delete b; // Also can write 0 and do it. bp3.write(uc(""), 0); bp3.finish(); b = bp3.getBuffer(); - std::cout << "size: " << b->getSize() << std::endl; + std::cout << "size: " << b->getSize() << '\n'; delete b; // Malloc buffer should behave similarly. @@ -147,7 +147,7 @@ main() bp4.getMallocBuffer(&mbuf, &len); assert(false); } catch (std::logic_error& e) { - std::cout << "malloc buffer logic error: " << e.what() << std::endl; + std::cout << "malloc buffer logic error: " << e.what() << '\n'; } bp4.finish(); bp4.getMallocBuffer(&mbuf, &len); @@ -160,10 +160,10 @@ main() assert(mbuf == nullptr); assert(len == 0); } catch (std::exception& e) { - std::cout << "unexpected exception: " << e.what() << std::endl; + std::cout << "unexpected exception: " << e.what() << '\n'; exit(2); } - std::cout << "done" << std::endl; + std::cout << "done" << '\n'; return 0; } diff --git a/libtests/closed_file_input_source.cc b/libtests/closed_file_input_source.cc index 8825335..c215d03 100644 --- a/libtests/closed_file_input_source.cc +++ b/libtests/closed_file_input_source.cc @@ -8,7 +8,7 @@ void check(std::string const& what, bool result) { if (!result) { - std::cout << "FAIL: " << what << std::endl; + std::cout << "FAIL: " << what << '\n'; } } @@ -73,6 +73,6 @@ main() std::cout << "testing with FileInputSource\n"; FileInputSource f("input"); do_tests(&f); - std::cout << "all assertions passed" << std::endl; + std::cout << "all assertions passed" << '\n'; return 0; } diff --git a/libtests/concatenate.cc b/libtests/concatenate.cc index 380d8cd..a3d4895 100644 --- a/libtests/concatenate.cc +++ b/libtests/concatenate.cc @@ -31,9 +31,9 @@ main(int argc, char* argv[]) auto b2_buf = b2.getBufferSharedPointer(); std::string result(reinterpret_cast(b2_buf->getBuffer()), b2_buf->getSize()); if (result == "-one--two-") { - std::cout << "concatenate test passed" << std::endl; + std::cout << "concatenate test passed" << '\n'; } else { - std::cout << "concatenate test failed: " << result << std::endl; + std::cout << "concatenate test failed: " << result << '\n'; } return 0; } diff --git a/libtests/crypto_provider.cc b/libtests/crypto_provider.cc index f28f163..2cebb15 100644 --- a/libtests/crypto_provider.cc +++ b/libtests/crypto_provider.cc @@ -47,7 +47,7 @@ class Potato: public QPDFCryptoImpl std::string SHA2_digest() override { - return std::string(); + return {}; } void RC4_init(const unsigned char* key_data, int key_len) override diff --git a/libtests/dct_compress.cc b/libtests/dct_compress.cc index 93979bd..46e1ab5 100644 --- a/libtests/dct_compress.cc +++ b/libtests/dct_compress.cc @@ -12,7 +12,7 @@ static void usage() { - std::cerr << "Usage: dct_compress infile outfile width height {rgb|cmyk|gray}" << std::endl; + std::cerr << "Usage: dct_compress infile outfile width height {rgb|cmyk|gray}" << '\n'; exit(2); } diff --git a/libtests/dct_uncompress.cc b/libtests/dct_uncompress.cc index c4255b5..fd2c812 100644 --- a/libtests/dct_uncompress.cc +++ b/libtests/dct_uncompress.cc @@ -10,7 +10,7 @@ int main(int argc, char* argv[]) { if (argc != 3) { - std::cerr << "Usage: dct_uncompress infile outfile" << std::endl; + std::cerr << "Usage: dct_uncompress infile outfile" << '\n'; exit(2); } diff --git a/libtests/flate.cc b/libtests/flate.cc index a14612c..7d8f821 100644 --- a/libtests/flate.cc +++ b/libtests/flate.cc @@ -53,7 +53,7 @@ run(char const* filename) def3->finish(); - std::cout << "bytes written to o3: " << count3->getCount() << std::endl; + std::cout << "bytes written to o3: " << count3->getCount() << '\n'; delete def3; delete inf3; @@ -76,14 +76,14 @@ run(char const* filename) // At this point, filename, filename.2, and filename.3 should have // identical contents. filename.1 should be a compressed version. - std::cout << "done" << std::endl; + std::cout << "done" << '\n'; } int main(int argc, char* argv[]) { if (argc != 2) { - std::cerr << "Usage: pipeline filename" << std::endl; + std::cerr << "Usage: pipeline filename" << '\n'; exit(2); } char* filename = argv[1]; @@ -91,7 +91,7 @@ main(int argc, char* argv[]) try { run(filename); } catch (std::exception& e) { - std::cout << e.what() << std::endl; + std::cout << e.what() << '\n'; } return 0; } diff --git a/libtests/hex.cc b/libtests/hex.cc index 5f11f87..98a1178 100644 --- a/libtests/hex.cc +++ b/libtests/hex.cc @@ -23,7 +23,7 @@ main() } decode.finish(); } catch (std::exception& e) { - std::cerr << e.what() << std::endl; + std::cerr << e.what() << '\n'; exit(2); } diff --git a/libtests/input_source.cc b/libtests/input_source.cc index 4111fd6..c1baeb5 100644 --- a/libtests/input_source.cc +++ b/libtests/input_source.cc @@ -47,7 +47,7 @@ Finder::check() void check(char const* description, bool expected, bool actual) { - std::cout << description << ": " << ((actual == expected) ? "PASS" : "FAIL") << std::endl; + std::cout << description << ": " << ((actual == expected) ? "PASS" : "FAIL") << '\n'; } int diff --git a/libtests/json.cc b/libtests/json.cc index aa726d6..7e49fa7 100644 --- a/libtests/json.cc +++ b/libtests/json.cc @@ -186,12 +186,12 @@ static void check_schema(JSON& obj, JSON& schema, unsigned long flags, bool exp, std::string const& description) { std::list errors; - std::cout << "--- " << description << std::endl; + std::cout << "--- " << description << '\n'; assert(exp == obj.checkSchema(schema, flags, errors)); for (auto const& error: errors) { - std::cout << error << std::endl; + std::cout << error << '\n'; } - std::cout << "---" << std::endl; + std::cout << "---" << '\n'; } static void diff --git a/libtests/json_handler.cc b/libtests/json_handler.cc index 2d3f986..255a8c0 100644 --- a/libtests/json_handler.cc +++ b/libtests/json_handler.cc @@ -8,43 +8,43 @@ static void print_null(std::string const& path) { - std::cout << path << ": null" << std::endl; + std::cout << path << ": null" << '\n'; } static void print_string(std::string const& path, std::string const& value) { - std::cout << path << ": string: " << value << std::endl; + std::cout << path << ": string: " << value << '\n'; } static void print_number(std::string const& path, std::string const& value) { - std::cout << path << ": number: " << value << std::endl; + std::cout << path << ": number: " << value << '\n'; } static void print_bool(std::string const& path, bool value) { - std::cout << path << ": bool: " << (value ? "true" : "false") << std::endl; + std::cout << path << ": bool: " << (value ? "true" : "false") << '\n'; } static void print_json(std::string const& path, JSON value) { - std::cout << path << ": json: " << value.unparse() << std::endl; + std::cout << path << ": json: " << value.unparse() << '\n'; } static JSONHandler::void_handler_t make_print_message(std::string msg) { - return [msg](std::string const& path) { std::cout << path << ": json: " << msg << std::endl; }; + return [msg](std::string const& path) { std::cout << path << ": json: " << msg << '\n'; }; } static void test_scalar() { - std::cout << "-- scalar --" << std::endl; + std::cout << "-- scalar --" << '\n'; JSONHandler h; h.addStringHandler(print_string); JSON j = JSON::parse("\"potato\""); @@ -97,7 +97,7 @@ make_all_handler() static void test_all() { - std::cout << "-- all --" << std::endl; + std::cout << "-- all --" << '\n'; auto h = make_all_handler(); /* cSpell: ignore phour */ JSON j = JSON::parse(R"({ @@ -110,7 +110,7 @@ test_all() "six": {"a": {"b": "quack", "Q": "baaa"}, "b": "moo"} })"); h->handle(".", j); - std::cerr << "-- fallback --" << std::endl; + std::cerr << "-- fallback --" << '\n'; j = JSON::parse(R"({ "five": "not-array" })"); @@ -120,14 +120,14 @@ test_all() static void test_errors() { - std::cout << "-- errors --" << std::endl; + std::cout << "-- errors --" << '\n'; auto h = make_all_handler(); auto t = [h](std::string const& msg, std::function fn) { try { fn(); assert(false); } catch (QPDFUsage& e) { - std::cout << msg << ": " << e.what() << std::endl; + std::cout << msg << ": " << e.what() << '\n'; } }; diff --git a/libtests/json_parse.cc b/libtests/json_parse.cc index 757b698..1a737bf 100644 --- a/libtests/json_parse.cc +++ b/libtests/json_parse.cc @@ -26,13 +26,13 @@ namespace void Reactor::dictionaryStart() { - std::cout << "dictionary start" << std::endl; + std::cout << "dictionary start" << '\n'; } void Reactor::arrayStart() { - std::cout << "array start" << std::endl; + std::cout << "array start" << '\n'; } void @@ -45,7 +45,7 @@ Reactor::containerEnd(JSON const& value) void Reactor::topLevelScalar() { - std::cout << "top-level scalar" << std::endl; + std::cout << "top-level scalar" << '\n'; } bool @@ -74,13 +74,13 @@ Reactor::arrayItem(JSON const& value) void Reactor::printItem(JSON const& j) { - std::cout << "[" << j.getStart() << ", " << j.getEnd() << "): " << j.unparse() << std::endl; + std::cout << "[" << j.getStart() << ", " << j.getEnd() << "): " << j.unparse() << '\n'; } static void usage() { - std::cerr << "Usage: json_parse file [--react]" << std::endl; + std::cerr << "Usage: json_parse file [--react]" << '\n'; exit(2); } @@ -102,9 +102,9 @@ main(int argc, char* argv[]) } try { FileInputSource is(filename); - std::cout << JSON::parse(is, reactor.get()).unparse() << std::endl; + std::cout << JSON::parse(is, reactor.get()).unparse() << '\n'; } catch (std::exception& e) { - std::cerr << "exception: " << filename << ": " << e.what() << std::endl; + std::cerr << "exception: " << filename << ": " << e.what() << '\n'; return 2; } return 0; diff --git a/libtests/lzw.cc b/libtests/lzw.cc index 3d255b2..19d0997 100644 --- a/libtests/lzw.cc +++ b/libtests/lzw.cc @@ -15,7 +15,7 @@ main(int argc, char* argv[]) } if (argc < 3) { - std::cerr << "Usage: lzw infile outfile [ --no-early-code-change ]" << std::endl; + std::cerr << "Usage: lzw infile outfile [ --no-early-code-change ]" << '\n'; exit(2); } @@ -41,7 +41,7 @@ main(int argc, char* argv[]) } decode.finish(); } catch (std::exception& e) { - std::cerr << e.what() << std::endl; + std::cerr << e.what() << '\n'; exit(2); } diff --git a/libtests/main_from_wmain.cc b/libtests/main_from_wmain.cc index b2290b2..bb8051e 100644 --- a/libtests/main_from_wmain.cc +++ b/libtests/main_from_wmain.cc @@ -8,7 +8,7 @@ wmain_test() // writable args and function args auto realmain = [](int argc, char* argv[]) { for (int i = 0; i < argc; ++i) { - std::cout << argv[i] << std::endl; + std::cout << argv[i] << '\n'; } return 0; }; @@ -28,7 +28,7 @@ cwmain_test() // const args and function args auto realmain = [](int argc, char const* const argv[]) { for (int i = 0; i < argc; ++i) { - std::cout << "const " << argv[i] << std::endl; + std::cout << "const " << argv[i] << '\n'; } return 0; }; @@ -49,7 +49,7 @@ main(int argc, char* argv[]) wmain_test(); cwmain_test(); } catch (std::exception& e) { - std::cout << "unexpected exception: " << e.what() << std::endl; + std::cout << "unexpected exception: " << e.what() << '\n'; } #endif // QPDF_NO_WCHAR_T diff --git a/libtests/matrix.cc b/libtests/matrix.cc index 70380f0..35f7ca0 100644 --- a/libtests/matrix.cc +++ b/libtests/matrix.cc @@ -9,7 +9,7 @@ check(QPDFMatrix const& m, std::string const& exp) { std::string u = m.unparse(); if (u != exp) { - std::cout << "got " << u << ", wanted " << exp << std::endl; + std::cout << "got " << u << ", wanted " << exp << '\n'; } } @@ -18,7 +18,7 @@ check_xy(double x, double y, std::string const& exp) { std::string u = (QUtil::double_to_string(x, 2) + " " + QUtil::double_to_string(y, 2)); if (u != exp) { - std::cout << "got " << u << ", wanted " << exp << std::endl; + std::cout << "got " << u << ", wanted " << exp << '\n'; } } @@ -32,7 +32,7 @@ check_rect(QPDFObjectHandle::Rectangle const& r, double llx, double lly, double (QUtil::double_to_string(llx, 2) + " " + QUtil::double_to_string(lly, 2) + " " + QUtil::double_to_string(urx, 2) + " " + QUtil::double_to_string(ury, 2)); if (actual != wanted) { - std::cout << "got " << actual << ", wanted " << wanted << std::endl; + std::cout << "got " << actual << ", wanted " << wanted << '\n'; } } @@ -78,6 +78,6 @@ main() m.translate(200, -100); check_rect(m.transformRectangle(QPDFObjectHandle::Rectangle(10, 20, 30, 50)), 50, 210, 80, 230); - std::cout << "matrix tests done" << std::endl; + std::cout << "matrix tests done" << '\n'; return 0; } diff --git a/libtests/md5.cc b/libtests/md5.cc index 93bfe58..afbc643 100644 --- a/libtests/md5.cc +++ b/libtests/md5.cc @@ -29,16 +29,16 @@ main(int, char*[]) "1234567890123456789012345678901234567890"); MD5 a; a.encodeFile("md5.in"); - std::cout << a.unparse() << std::endl; + std::cout << a.unparse() << '\n'; MD5 b; b.encodeFile("md5.in", 100); - std::cout << b.unparse() << std::endl; + std::cout << b.unparse() << '\n'; - std::cout << MD5::checkDataChecksum("900150983cd24fb0d6963f7d28e17f72", "abc", 3) << std::endl - << MD5::checkFileChecksum("5f4b4321873433daae578f85c72f9e74", "md5.in") << std::endl - << MD5::checkFileChecksum("6f4b4321873433daae578f85c72f9e74", "md5.in") << std::endl - << MD5::checkDataChecksum("000150983cd24fb0d6963f7d28e17f72", "abc", 3) << std::endl - << MD5::checkFileChecksum("6f4b4321873433daae578f85c72f9e74", "glerbl") << std::endl; + std::cout << MD5::checkDataChecksum("900150983cd24fb0d6963f7d28e17f72", "abc", 3) << '\n' + << MD5::checkFileChecksum("5f4b4321873433daae578f85c72f9e74", "md5.in") << '\n' + << MD5::checkFileChecksum("6f4b4321873433daae578f85c72f9e74", "md5.in") << '\n' + << MD5::checkDataChecksum("000150983cd24fb0d6963f7d28e17f72", "abc", 3) << '\n' + << MD5::checkFileChecksum("6f4b4321873433daae578f85c72f9e74", "glerbl") << '\n'; Pl_Discard d; Pl_MD5 p("MD5", &d); @@ -63,7 +63,7 @@ main(int, char*[]) p2.write(buf, len); if (i == 1) { // Partial digest -- resets after each call to write - std::cout << p.getHexDigest() << std::endl; + std::cout << p.getHexDigest() << '\n'; } } } @@ -72,10 +72,10 @@ main(int, char*[]) p2.finish(); // Make sure calling getHexDigest twice with no intervening // writes results in the same result each time. - std::cout << p.getHexDigest() << std::endl; - std::cout << p.getHexDigest() << std::endl; + std::cout << p.getHexDigest() << '\n'; + std::cout << p.getHexDigest() << '\n'; } - std::cout << p2.getHexDigest() << std::endl; + std::cout << p2.getHexDigest() << '\n'; return 0; } diff --git a/libtests/nntree.cc b/libtests/nntree.cc index c2b35dc..ac6ff98 100644 --- a/libtests/nntree.cc +++ b/libtests/nntree.cc @@ -20,7 +20,7 @@ report(QPDF& q, QPDFObjectHandle oh, long long item, long long exp_item) auto show = [&failed, &oh, &item]() { if (!failed) { failed = true; - std::cout << "key = " << item << ", oh = " << oh.unparseResolved() << std::endl; + std::cout << "key = " << item << ", oh = " << oh.unparseResolved() << '\n'; } }; @@ -37,11 +37,11 @@ report(QPDF& q, QPDFObjectHandle oh, long long item, long long exp_item) if (i1_wanted != i1_actual) { show(); - std::cout << "i1: wanted " << i1_wanted << ", got " << i1_actual << std::endl; + std::cout << "i1: wanted " << i1_wanted << ", got " << i1_actual << '\n'; } if (i2_wanted != i2_actual) { show(); - std::cout << "i2: wanted " << i2_wanted << ", got " << i2_actual << std::endl; + std::cout << "i2: wanted " << i2_wanted << ", got " << i2_actual << '\n'; } return failed; @@ -106,7 +106,7 @@ test_bsearch() r(d, 25, 20); if (!any_failures) { - std::cout << "bsearch tests passed" << std::endl; + std::cout << "bsearch tests passed" << '\n'; } } @@ -128,7 +128,7 @@ check_find(QPDFNameTreeObjectHelper& nh, std::string const& key, bool prev_if_no } else { std::cout << (*i).first << " -> " << (*i).second.unparse(); } - std::cout << std::endl; + std::cout << '\n'; } void @@ -183,13 +183,13 @@ test_depth() } QPDFNameTreeObjectHelper nh(n0, q); - std::cout << "--- forward ---" << std::endl; + std::cout << "--- forward ---" << '\n'; for (auto i: nh) { - std::cout << i.first << " -> " << i.second.unparse() << std::endl; + std::cout << i.first << " -> " << i.second.unparse() << '\n'; } - std::cout << "--- backward ---" << std::endl; + std::cout << "--- backward ---" << '\n'; for (auto i = nh.last(); i.valid(); --i) { - std::cout << (*i).first << " -> " << (*i).second.unparse() << std::endl; + std::cout << (*i).first << " -> " << (*i).second.unparse() << '\n'; } // Find diff --git a/libtests/numrange.cc b/libtests/numrange.cc index ded0332..b3ae05d 100644 --- a/libtests/numrange.cc +++ b/libtests/numrange.cc @@ -5,14 +5,14 @@ static void test_numrange(char const* range) { if (range == nullptr) { - std::cout << "null" << std::endl; + std::cout << "null" << '\n'; } else { std::vector result = QUtil::parse_numrange(range, 15); std::cout << "numeric range " << range << " ->"; for (int i: result) { std::cout << " " << i; } - std::cout << std::endl; + std::cout << '\n'; } } @@ -22,7 +22,7 @@ main(int argc, char* argv[]) try { test_numrange(argv[1]); } catch (std::exception& e) { - std::cout << e.what() << std::endl; + std::cout << e.what() << '\n'; return 2; } diff --git a/libtests/pdf_version.cc b/libtests/pdf_version.cc index 5db444b..42b20c2 100644 --- a/libtests/pdf_version.cc +++ b/libtests/pdf_version.cc @@ -48,6 +48,6 @@ main() assert(PDFVersion(2, 0) == PDFVersion(2, 0)); assert(PDFVersion(2, 0, 1) == PDFVersion(2, 0, 1)); - std::cout << "PDFVersion assertions passed" << std::endl; + std::cout << "PDFVersion assertions passed" << '\n'; return 0; } diff --git a/libtests/pl_function.cc b/libtests/pl_function.cc index 2829671..bfde64d 100644 --- a/libtests/pl_function.cc +++ b/libtests/pl_function.cc @@ -18,7 +18,7 @@ f(unsigned char const* data, size_t len, void* udata) { auto c = reinterpret_cast(udata); ++c->count; - std::cout << "got " << data << "(" << len << ")" << std::endl; + std::cout << "got " << data << "(" << len << ")" << '\n'; if (c->count == 3) { return 1; } @@ -30,7 +30,7 @@ g(char const* data, size_t len, void* udata) { auto c = reinterpret_cast(udata); ++c->count; - std::cout << "signed got " << data << "(" << len << ")" << std::endl; + std::cout << "signed got " << data << "(" << len << ")" << '\n'; if (c->count == 2) { return 2; } @@ -41,7 +41,7 @@ int main(int argc, char* argv[]) { Pl_Function p1("p1", nullptr, [](unsigned char const* data, size_t len) { - std::cout << "p1: " << len << ": " << data << std::endl; + std::cout << "p1: " << len << ": " << data << '\n'; }); p1.write(reinterpret_cast("potato"), 6); @@ -49,7 +49,7 @@ main(int argc, char* argv[]) Pl_String ps("string", nullptr, s); Pl_Base64 b("base64", &ps, Pl_Base64::a_encode); Pl_Function p2("p2", &b, [](unsigned char const* data, size_t len) { - std::cout << "p2: " << len << ": " << data << std::endl; + std::cout << "p2: " << len << ": " << data << '\n'; }); p2.write(reinterpret_cast("salad"), 5); p2.finish(); @@ -63,7 +63,7 @@ main(int argc, char* argv[]) p3 << "three"; assert(false); } catch (std::runtime_error& e) { - std::cout << "three threw " << e.what() << std::endl; + std::cout << "three threw " << e.what() << '\n'; } p3 << "four"; p3.finish(); @@ -76,7 +76,7 @@ main(int argc, char* argv[]) p4 << "salad"; assert(false); } catch (std::runtime_error& e) { - std::cout << "salad threw " << e.what() << std::endl; + std::cout << "salad threw " << e.what() << '\n'; } p4 << "quack"; p4.finish(); diff --git a/libtests/pointer_holder.cc b/libtests/pointer_holder.cc index 641cd0b..f86b01c 100644 --- a/libtests/pointer_holder.cc +++ b/libtests/pointer_holder.cc @@ -26,24 +26,24 @@ int Object::next_id = 0; Object::Object() { this->id = ++next_id; - std::cout << "created Object, id " << this->id << std::endl; + std::cout << "created Object, id " << this->id << '\n'; } Object::~Object() { - std::cout << "destroyed Object, id " << this->id << std::endl; + std::cout << "destroyed Object, id " << this->id << '\n'; } void Object::hello() { - std::cout << "calling Object::hello for " << this->id << std::endl; + std::cout << "calling Object::hello for " << this->id << '\n'; } void Object::hello() const { - std::cout << "calling Object::hello const for " << this->id << std::endl; + std::cout << "calling Object::hello const for " << this->id << '\n'; } typedef PointerHolder ObjectHolder; @@ -71,27 +71,27 @@ test_ph() ObjectHolder oh0; { - std::cout << "hello" << std::endl; + std::cout << "hello" << '\n'; auto* o1 = new Object; ObjectHolder oh1(o1); - std::cout << "oh1 refcount = " << oh1.getRefcount() << std::endl; + std::cout << "oh1 refcount = " << oh1.getRefcount() << '\n'; ObjectHolder oh2(oh1); - std::cout << "oh1 refcount = " << oh1.getRefcount() << std::endl; - std::cout << "oh2 refcount = " << oh2.use_count() << std::endl; + std::cout << "oh1 refcount = " << oh1.getRefcount() << '\n'; + std::cout << "oh2 refcount = " << oh2.use_count() << '\n'; ObjectHolder oh3(new Object); ObjectHolder oh4; ObjectHolder oh5; - std::cout << "oh5 refcount = " << oh5.getRefcount() << std::endl; + std::cout << "oh5 refcount = " << oh5.getRefcount() << '\n'; if (oh4 == oh5) { - std::cout << "nulls equal" << std::endl; + std::cout << "nulls equal" << '\n'; } oh3 = oh1; oh4 = oh2; if (oh3 == oh4) { - std::cout << "equal okay" << std::endl; + std::cout << "equal okay" << '\n'; } if ((!(oh3 < oh4)) && (!(oh4 < oh3))) { - std::cout << "less than okay" << std::endl; + std::cout << "less than okay" << '\n'; } ol1.push_back(oh3); ol1.push_back(oh3); @@ -107,9 +107,9 @@ test_ph() callHello(ol1.front()); callHelloWithGet(ol1.front()); ol1.pop_front(); - std::cout << "array" << std::endl; + std::cout << "array" << '\n'; PointerHolder o_arr1_ph(true, new Object[2]); - std::cout << "goodbye" << std::endl; + std::cout << "goodbye" << '\n'; } PointerHolder @@ -165,7 +165,7 @@ ph_sp_compat() { // Ensure bidirectional compatibility between PointerHolder and // shared_ptr. - std::cout << "compat" << std::endl; + std::cout << "compat" << '\n'; PointerHolder ph_from_ph = make_object_ph(); std::shared_ptr sp_from_ph = make_object_ph(); PointerHolder ph_from_sp = make_object_sp(); @@ -184,21 +184,21 @@ ph_sp_compat() hello_ph_const(sp_const_from_sp); PointerHolder arr1_ph; { - std::cout << "initialize ph array from shared_ptr" << std::endl; + std::cout << "initialize ph array from shared_ptr" << '\n'; std::shared_ptr arr1(new Object[2], std::default_delete()); arr1_ph = arr1; } - std::cout << "delete ph array" << std::endl; + std::cout << "delete ph array" << '\n'; arr1_ph = nullptr; std::shared_ptr arr2_sp; { - std::cout << "initialize sp array from PointerHolder" << std::endl; + std::cout << "initialize sp array from PointerHolder" << '\n'; PointerHolder arr2(true, new Object[2]); arr2_sp = arr2; } - std::cout << "delete sp array" << std::endl; + std::cout << "delete sp array" << '\n'; arr2_sp = nullptr; - std::cout << "end compat" << std::endl; + std::cout << "end compat" << '\n'; } std::list> @@ -224,13 +224,13 @@ get_sp_list() void ph_sp_containers() { - std::cout << "containers" << std::endl; + std::cout << "containers" << '\n'; // Demonstrate that using auto makes it easy to switch interfaces // from using a container of one shared pointer type to a // container of the other. auto phl1 = get_ph_list(); auto phl2 = get_sp_list(); - std::cout << "end containers" << std::endl; + std::cout << "end containers" << '\n'; } int diff --git a/libtests/predictors.cc b/libtests/predictors.cc index f41cf5c..25e4a5a 100644 --- a/libtests/predictors.cc +++ b/libtests/predictors.cc @@ -39,7 +39,7 @@ run(char const* filename, samples_per_pixel, bits_per_sample); } else { - std::cerr << "unknown filter " << filter << std::endl; + std::cerr << "unknown filter " << filter << '\n'; exit(2); } assert((2 * (columns + 1)) < 1024); @@ -69,7 +69,7 @@ run(char const* filename, fclose(o1); fclose(in); - std::cout << "done" << std::endl; + std::cout << "done" << '\n'; } int @@ -77,7 +77,7 @@ main(int argc, char* argv[]) { if (argc != 7) { std::cerr << "Usage: predictor {png|tiff} {en,de}code filename" - << " columns samples-per-pixel bits-per-sample" << std::endl; + << " columns samples-per-pixel bits-per-sample" << '\n'; exit(2); } char* filter = argv[1]; @@ -95,7 +95,7 @@ main(int argc, char* argv[]) QIntC::to_uint(bits_per_sample), QIntC::to_uint(samples_per_pixel)); } catch (std::exception& e) { - std::cout << e.what() << std::endl; + std::cout << e.what() << '\n'; } return 0; } diff --git a/libtests/qintc.cc b/libtests/qintc.cc index d7711c2..f548324 100644 --- a/libtests/qintc.cc +++ b/libtests/qintc.cc @@ -18,7 +18,7 @@ try_convert_real(char const* description, bool exp_pass, To (*fn)(From const&), std::cout << description << ": " << e.what(); passed = false; } - std::cout << ((passed == exp_pass) ? " PASSED" : " FAILED") << std::endl; + std::cout << ((passed == exp_pass) ? " PASSED" : " FAILED") << '\n'; } #define try_range_check(exp_pass, a, b) try_range_check_real(#a " + " #b, exp_pass, a, b) @@ -36,7 +36,7 @@ try_range_check_real(char const* description, bool exp_pass, T const& a, T const std::cout << description << ": " << e.what(); passed = false; } - std::cout << ((passed == exp_pass) ? " PASSED" : " FAILED") << std::endl; + std::cout << ((passed == exp_pass) ? " PASSED" : " FAILED") << '\n'; } #define try_range_check_subtract(exp_pass, a, b) \ @@ -55,7 +55,7 @@ try_range_check_subtract_real(char const* description, bool exp_pass, T const& a std::cout << description << ": " << e.what(); passed = false; } - std::cout << ((passed == exp_pass) ? " PASSED" : " FAILED") << std::endl; + std::cout << ((passed == exp_pass) ? " PASSED" : " FAILED") << '\n'; } int diff --git a/libtests/qutil.cc b/libtests/qutil.cc index 78ae82c..30dcd1e 100644 --- a/libtests/qutil.cc +++ b/libtests/qutil.cc @@ -32,13 +32,13 @@ test_to_number(char const* str, int_T wanted, bool error, int_T (*fn)(char const } if (threw) { if (error) { - std::cout << str << " to int threw (" << msg << "): PASSED" << std::endl; + std::cout << str << " to int threw (" << msg << "): PASSED" << '\n'; } else { std::cout << str << " to int threw but wanted " << wanted << std::endl; } } else { if (worked) { - std::cout << str << " to int: PASSED" << std::endl; + std::cout << str << " to int: PASSED" << '\n'; } else { std::cout << str << " to int failed; got " << result << std::endl; } @@ -97,51 +97,51 @@ string_conversion_test() // Make sure the code produces consistent results even if we load // a non-C locale. set_locale(); - std::cout << QUtil::int_to_string(16059) << std::endl - << QUtil::int_to_string(16059, 7) << std::endl - << QUtil::int_to_string(16059, -7) << std::endl - << QUtil::double_to_string(3.14159, 0, false) << std::endl - << QUtil::double_to_string(3.14159, 3) << std::endl - << QUtil::double_to_string(1000.123, -1024, false) << std::endl - << QUtil::double_to_string(.1234, 5, false) << std::endl - << QUtil::double_to_string(.0001234, 5) << std::endl - << QUtil::double_to_string(.123456, 5) << std::endl - << QUtil::double_to_string(.000123456, 5) << std::endl - << QUtil::double_to_string(1.01020, 5, true) << std::endl - << QUtil::double_to_string(1.00000, 5, true) << std::endl - << QUtil::double_to_string(1, 5, true) << std::endl - << QUtil::double_to_string(1, 5, false) << std::endl - << QUtil::double_to_string(10, 2, false) << std::endl - << QUtil::double_to_string(10, 2, true) << std::endl - << QUtil::int_to_string_base(16059, 10) << std::endl - << QUtil::int_to_string_base(16059, 8) << std::endl - << QUtil::int_to_string_base(16059, 16) << std::endl - << QUtil::int_to_string_base(5000093552LL, 10) << std::endl; + std::cout << QUtil::int_to_string(16059) << '\n' + << QUtil::int_to_string(16059, 7) << '\n' + << QUtil::int_to_string(16059, -7) << '\n' + << QUtil::double_to_string(3.14159, 0, false) << '\n' + << QUtil::double_to_string(3.14159, 3) << '\n' + << QUtil::double_to_string(1000.123, -1024, false) << '\n' + << QUtil::double_to_string(.1234, 5, false) << '\n' + << QUtil::double_to_string(.0001234, 5) << '\n' + << QUtil::double_to_string(.123456, 5) << '\n' + << QUtil::double_to_string(.000123456, 5) << '\n' + << QUtil::double_to_string(1.01020, 5, true) << '\n' + << QUtil::double_to_string(1.00000, 5, true) << '\n' + << QUtil::double_to_string(1, 5, true) << '\n' + << QUtil::double_to_string(1, 5, false) << '\n' + << QUtil::double_to_string(10, 2, false) << '\n' + << QUtil::double_to_string(10, 2, true) << '\n' + << QUtil::int_to_string_base(16059, 10) << '\n' + << QUtil::int_to_string_base(16059, 8) << '\n' + << QUtil::int_to_string_base(16059, 16) << '\n' + << QUtil::int_to_string_base(5000093552LL, 10) << '\n'; std::string embedded_null = "one"; embedded_null += '\0'; embedded_null += "two"; - std::cout << embedded_null.c_str() << std::endl; - std::cout << embedded_null.length() << std::endl; + std::cout << embedded_null.c_str() << '\n'; + std::cout << embedded_null.length() << '\n'; char* tmp = QUtil::copy_string(embedded_null); if (memcmp(tmp, embedded_null.c_str(), 7) == 0) { - std::cout << "compare okay" << std::endl; + std::cout << "compare okay" << '\n'; } else { - std::cout << "compare failed" << std::endl; + std::cout << "compare failed" << '\n'; } delete[] tmp; // Also test with make_shared_cstr and make_unique_cstr auto tmp2 = QUtil::make_shared_cstr(embedded_null); if (memcmp(tmp2.get(), embedded_null.c_str(), 7) == 0) { - std::cout << "compare okay" << std::endl; + std::cout << "compare okay" << '\n'; } else { - std::cout << "compare failed" << std::endl; + std::cout << "compare failed" << '\n'; } auto tmp3 = QUtil::make_unique_cstr(embedded_null); if (memcmp(tmp3.get(), embedded_null.c_str(), 7) == 0) { - std::cout << "compare okay" << std::endl; + std::cout << "compare okay" << '\n'; } else { - std::cout << "compare failed" << std::endl; + std::cout << "compare failed" << '\n'; } std::string int_max_str = QUtil::int_to_string(INT_MAX); @@ -171,11 +171,11 @@ void os_wrapper_test() { try { - std::cout << "before remove" << std::endl; + std::cout << "before remove" << '\n'; QUtil::os_wrapper("remove file", remove("/this/file/does/not/exist")); - std::cout << "after remove" << std::endl; + std::cout << "after remove" << '\n'; } catch (std::runtime_error& s) { - std::cout << "exception: " << s.what() << std::endl; + std::cout << "exception: " << s.what() << '\n'; } } @@ -183,12 +183,12 @@ void fopen_wrapper_test() { try { - std::cout << "before fopen" << std::endl; + std::cout << "before fopen" << '\n'; FILE* f = QUtil::safe_fopen("/this/file/does/not/exist", "r"); - std::cout << "after fopen" << std::endl; + std::cout << "after fopen" << '\n'; (void)fclose(f); } catch (QPDFSystemError& s) { - std::cout << "exception: " << s.what() << std::endl; + std::cout << "exception: " << s.what() << '\n'; assert(s.getErrno() != 0); } @@ -200,10 +200,9 @@ void getenv_test() { std::string val; - std::cout << "IN_TESTSUITE: " << QUtil::get_env("IN_TESTSUITE", &val) << ": " << val - << std::endl; + std::cout << "IN_TESTSUITE: " << QUtil::get_env("IN_TESTSUITE", &val) << ": " << val << '\n'; // Hopefully this environment variable is not defined. - std::cout << "HAGOOGAMAGOOGLE: " << QUtil::get_env("HAGOOGAMAGOOGLE") << std::endl; + std::cout << "HAGOOGAMAGOOGLE: " << QUtil::get_env("HAGOOGAMAGOOGLE") << '\n'; } static void @@ -223,7 +222,7 @@ print_utf8(unsigned long val) static_cast(static_cast(ch)), 16, 2); } } - std::cout << std::endl; + std::cout << '\n'; // Boundary conditions for QUtil::get_next_utf8_codepoint, which is // also tested indirectly through test_pdf_unicode.cc. @@ -264,7 +263,7 @@ to_utf8_test() try { print_utf8(0x80000000UL); } catch (std::runtime_error& e) { - std::cout << "0x80000000: " << e.what() << std::endl; + std::cout << "0x80000000: " << e.what() << '\n'; } // Overlong characters: characters represented by more bytes than necessary. @@ -296,7 +295,7 @@ print_utf16(unsigned long val) << QUtil::int_to_string_base( static_cast(static_cast(ch)), 16, 2); } - std::cout << std::endl; + std::cout << '\n'; } void @@ -311,24 +310,24 @@ to_utf16_test() print_utf16(0x80000000UL); std::string s(QUtil::utf8_to_utf16("\xcf\x80")); - std::cout << QUtil::utf16_to_utf8(s) << std::endl; - std::cout << QUtil::utf16_to_utf8(s + ".") << std::endl; - std::cout << "LE: " << QUtil::utf16_to_utf8("\xff\xfe\xc0\x03") << std::endl; + std::cout << QUtil::utf16_to_utf8(s) << '\n'; + std::cout << QUtil::utf16_to_utf8(s + ".") << '\n'; + std::cout << "LE: " << QUtil::utf16_to_utf8("\xff\xfe\xc0\x03") << '\n'; } void utf8_to_ascii_test() { char const* input = "\302\277Does \317\200 have fingers?"; - std::cout << input << std::endl - << QUtil::utf8_to_ascii(input) << std::endl - << QUtil::utf8_to_ascii(input, '*') << std::endl; + std::cout << input << '\n' + << QUtil::utf8_to_ascii(input) << '\n' + << QUtil::utf8_to_ascii(input, '*') << '\n'; std::string a = QUtil::utf8_to_win_ansi(input, '*'); std::string b = QUtil::utf8_to_mac_roman(input, '*'); std::cout << "<" << QUtil::int_to_string_base(static_cast(a.at(0)), 16, 2) << ">" - << a.substr(1) << std::endl + << a.substr(1) << '\n' << "<" << QUtil::int_to_string_base(static_cast(b.at(0)), 16, 2) << ">" - << b.substr(1) << std::endl; + << b.substr(1) << '\n'; } void @@ -349,7 +348,7 @@ transcoding_test( back = (*from_utf8)(out, '?'); if (back != wanted) { std::cout << i << ": " << in << " -> " << out << " -> " << back << " (wanted " << wanted - << ")" << std::endl; + << ")" << '\n'; } } } @@ -363,7 +362,7 @@ check_analyze(std::string const& str, bool has8bit, bool utf8, bool utf16) QUtil::analyze_encoding(str, has_8bit_chars, is_valid_utf8, is_utf16); if (!((has_8bit_chars == has8bit) && (is_valid_utf8 == utf8) && (is_utf16 == utf16))) { std::cout << "analysis failed: " << str << ": 8bit: " << has_8bit_chars - << ", utf8: " << is_valid_utf8 << ", utf16: " << is_utf16 << std::endl; + << ", utf8: " << is_valid_utf8 << ", utf16: " << is_utf16 << '\n'; } } @@ -373,7 +372,7 @@ print_alternatives(std::string const& str) std::vector result = QUtil::possible_repaired_encodings(str); size_t n = result.size(); for (size_t i = 0; i < n; ++i) { - std::cout << i << ": " << QUtil::hex_encode(result.at(i)) << std::endl; + std::cout << i << ": " << QUtil::hex_encode(result.at(i)) << '\n'; } } @@ -381,20 +380,20 @@ void transcoding_test() { transcoding_test(&QUtil::pdf_doc_to_utf8, &QUtil::utf8_to_pdf_doc, 127, 160, "\x9f"); - std::cout << "bidirectional pdf doc done" << std::endl; + std::cout << "bidirectional pdf doc done" << '\n'; transcoding_test(&QUtil::pdf_doc_to_utf8, &QUtil::utf8_to_pdf_doc, 24, 31, "?"); - std::cout << "bidirectional pdf doc low done" << std::endl; + std::cout << "bidirectional pdf doc low done" << '\n'; transcoding_test(&QUtil::win_ansi_to_utf8, &QUtil::utf8_to_win_ansi, 128, 160, "?"); - std::cout << "bidirectional win ansi done" << std::endl; + std::cout << "bidirectional win ansi done" << '\n'; transcoding_test(&QUtil::mac_roman_to_utf8, &QUtil::utf8_to_mac_roman, 128, 255, "?"); - std::cout << "bidirectional mac roman done" << std::endl; + std::cout << "bidirectional mac roman done" << '\n'; check_analyze("pi = \317\200", true, true, false); check_analyze("pi != \317", true, false, false); check_analyze("pi != 22/7", false, false, false); check_analyze("\xE0\x80\x82", true, false, false); check_analyze(std::string("\xfe\xff\x00\x51", 4), true, false, true); check_analyze(std::string("\xff\xfe\x51\x00", 4), true, false, true); - std::cout << "analysis done" << std::endl; + std::cout << "analysis done" << '\n'; std::string input1("a\302\277b"); std::string input2("a\317\200b"); std::string input3("ab"); @@ -411,7 +410,7 @@ transcoding_test() assert(QUtil::utf8_to_pdf_doc(input1, output)); assert(!QUtil::utf8_to_pdf_doc(input2, output)); assert(QUtil::utf8_to_pdf_doc(input3, output)); - std::cout << "alternatives" << std::endl; + std::cout << "alternatives" << '\n'; // char name mac win pdf-doc // U+0192 florin 304 203 206 // U+00A9 copyright 251 251 251 @@ -422,18 +421,18 @@ transcoding_test() print_alternatives(pdfdoc); print_alternatives(utf8); print_alternatives("quack"); - std::cout << "done alternatives" << std::endl; + std::cout << "done alternatives" << '\n'; // These are characters are either valid in PDFDoc and invalid in // UTF-8 or the other way around. std::string other("w\x18w\x19w\x1aw\x1bw\x1cw\x1dw\x1ew\x1fw\x7fw"); // cSpell: ignore xadw std::string other_doc = other + "\x9fw\xadw"; - std::cout << QUtil::pdf_doc_to_utf8(other_doc) << std::endl; + std::cout << QUtil::pdf_doc_to_utf8(other_doc) << '\n'; std::string other_utf8 = other + QUtil::toUTF8(0x9f) + "w" + QUtil::toUTF8(0xad) + "w"; std::string other_to_utf8; assert(!QUtil::utf8_to_pdf_doc(other_utf8, other_to_utf8)); - std::cout << other_to_utf8 << std::endl; - std::cout << "done other characters" << std::endl; + std::cout << other_to_utf8 << '\n'; + std::cout << "done other characters" << '\n'; // These valid UTF8 strings when converted to PDFDoc would end up // with a byte sequence that would be recognized as UTF-8 or // UTF-16 rather than PDFDoc. A special case is required to store @@ -455,7 +454,7 @@ void print_whoami(char const* str) { auto dup = QUtil::make_unique_cstr(str); - std::cout << QUtil::getWhoami(dup.get()) << std::endl; + std::cout << QUtil::getWhoami(dup.get()) << '\n'; } void @@ -473,7 +472,7 @@ assert_same_file(char const* file1, char const* file2, bool expected) bool actual = QUtil::same_file(file1, file2); std::cout << "file1: -" << (file1 ? file1 : "(null)") << "-, file2: -" << (file2 ? file2 : "(null)") << "-; same: " << actual << ": " - << ((actual == expected) ? "PASS" : "FAIL") << std::endl; + << ((actual == expected) ? "PASS" : "FAIL") << '\n'; } void @@ -501,7 +500,7 @@ path_test() auto check = [](bool print, std::string const& a, std::string const& b) { auto result = QUtil::path_basename(a); if (print) { - std::cout << a << " -> " << result << std::endl; + std::cout << a << " -> " << result << '\n'; } assert(result == b); }; @@ -523,7 +522,7 @@ read_from_file_test() { std::list lines = QUtil::read_lines_from_file("other-file"); for (auto const& line: lines) { - std::cout << line << std::endl; + std::cout << line << '\n'; } // Test the other versions and make sure we get the same results { @@ -561,7 +560,7 @@ read_from_file_test() std::shared_ptr buf; size_t size = 0; QUtil::read_file_into_memory("other-file", buf, size); - std::cout << "read " << size << " bytes" << std::endl; + std::cout << "read " << size << " bytes" << '\n'; char const* p = buf.get(); assert(size == 24652); assert(memcmp(p, "This file is used for qutil testing.", 36) == 0); @@ -575,7 +574,7 @@ read_from_file_test() assert(memcmp(buf2->getBuffer(), p, size) == 0); auto s = QUtil::read_file_into_string("other-file"); - std::cout << "read " << s.size() << " bytes" << std::endl; + std::cout << "read " << s.size() << " bytes" << '\n'; assert(s.size() == 24652); assert(s.substr(0, 36) == "This file is used for qutil testing."); assert(s.substr(24641, 10) == "very long."); @@ -587,7 +586,7 @@ assert_hex_encode(std::string const& input, std::string const& expected) std::string actual = QUtil::hex_encode(input); if (expected != actual) { std::cout << "hex encode " << input << ": expected = " << expected - << "; actual = " << actual << std::endl; + << "; actual = " << actual << '\n'; } } @@ -597,7 +596,7 @@ assert_hex_decode(std::string const& input, std::string const& expected) std::string actual = QUtil::hex_decode(input); if (expected != actual) { std::cout << "hex encode " << input << ": expected = " << expected - << "; actual = " << actual << std::endl; + << "; actual = " << actual << '\n'; } } @@ -639,31 +638,31 @@ rename_delete_test() } catch (QPDFSystemError&) { } assert_no_file("old\xcf\x80"); - std::cout << "create file" << std::endl; + std::cout << "create file" << '\n'; ; FILE* f1 = QUtil::safe_fopen("old\xcf\x80", "w"); fprintf(f1, "one"); fclose(f1); QUtil::read_file_into_memory("old\xcf\x80", buf, size); assert(memcmp(buf.get(), "one", 3) == 0); - std::cout << "rename file" << std::endl; + std::cout << "rename file" << '\n'; ; QUtil::rename_file("old\xcf\x80", "old\xcf\x80.~tmp"); QUtil::read_file_into_memory("old\xcf\x80.~tmp", buf, size); assert(memcmp(buf.get(), "one", 3) == 0); assert_no_file("old\xcf\x80"); - std::cout << "create file" << std::endl; + std::cout << "create file" << '\n'; ; f1 = QUtil::safe_fopen("old\xcf\x80", "w"); fprintf(f1, "two"); fclose(f1); - std::cout << "rename over existing" << std::endl; + std::cout << "rename over existing" << '\n'; ; QUtil::rename_file("old\xcf\x80", "old\xcf\x80.~tmp"); QUtil::read_file_into_memory("old\xcf\x80.~tmp", buf, size); assert(memcmp(buf.get(), "two", 3) == 0); assert_no_file("old\xcf\x80"); - std::cout << "delete file" << std::endl; + std::cout << "delete file" << '\n'; ; QUtil::remove_file("old\xcf\x80.~tmp"); assert_no_file("old\xcf\x80"); @@ -676,7 +675,7 @@ timestamp_test() auto check = [](QUtil::QPDFTime const& t) { std::string pdf = QUtil::qpdf_time_to_pdf_time(t); std::string iso8601 = QUtil::qpdf_time_to_iso8601(t); - std::cout << pdf << std::endl << iso8601 << std::endl; + std::cout << pdf << '\n' << iso8601 << '\n'; QUtil::QPDFTime t2; std::string iso8601_2; assert(QUtil::pdf_time_to_qpdf_time(pdf, &t2)); @@ -704,7 +703,7 @@ is_long_long_test() { auto check = [](char const* s, bool v) { if (QUtil::is_long_long(s) != v) { - std::cout << "failed: " << s << std::endl; + std::cout << "failed: " << s << '\n'; } }; check("12312312", true); @@ -719,7 +718,7 @@ is_long_long_test() check("123123123123123123123123123123123123", false); check("potato", false); check("0123", false); - std::cout << "done" << std::endl; + std::cout << "done" << '\n'; } void @@ -731,49 +730,49 @@ memory_usage_test() auto u2 = QUtil::get_max_memory_usage(); assert(u2 > u1); } - std::cout << "memory usage okay" << std::endl; + std::cout << "memory usage okay" << '\n'; } int main(int argc, char* argv[]) { try { - std::cout << "---- string conversion" << std::endl; + std::cout << "---- string conversion" << '\n'; string_conversion_test(); - std::cout << "---- os wrapper" << std::endl; + std::cout << "---- os wrapper" << '\n'; os_wrapper_test(); - std::cout << "---- fopen" << std::endl; + std::cout << "---- fopen" << '\n'; fopen_wrapper_test(); - std::cout << "---- getenv" << std::endl; + std::cout << "---- getenv" << '\n'; getenv_test(); - std::cout << "---- utf8" << std::endl; + std::cout << "---- utf8" << '\n'; to_utf8_test(); - std::cout << "---- utf16" << std::endl; + std::cout << "---- utf16" << '\n'; to_utf16_test(); - std::cout << "---- utf8_to_ascii" << std::endl; + std::cout << "---- utf8_to_ascii" << '\n'; utf8_to_ascii_test(); - std::cout << "---- transcoding" << std::endl; + std::cout << "---- transcoding" << '\n'; transcoding_test(); - std::cout << "---- whoami" << std::endl; + std::cout << "---- whoami" << '\n'; get_whoami_test(); - std::cout << "---- file" << std::endl; + std::cout << "---- file" << '\n'; same_file_test(); - std::cout << "---- path" << std::endl; + std::cout << "---- path" << '\n'; path_test(); - std::cout << "---- read from file" << std::endl; + std::cout << "---- read from file" << '\n'; read_from_file_test(); - std::cout << "---- hex encode/decode" << std::endl; + std::cout << "---- hex encode/decode" << '\n'; hex_encode_decode_test(); - std::cout << "---- rename/delete" << std::endl; + std::cout << "---- rename/delete" << '\n'; rename_delete_test(); - std::cout << "---- timestamp" << std::endl; + std::cout << "---- timestamp" << '\n'; timestamp_test(); - std::cout << "---- is_long_long" << std::endl; + std::cout << "---- is_long_long" << '\n'; is_long_long_test(); - std::cout << "---- memory usage" << std::endl; + std::cout << "---- memory usage" << '\n'; memory_usage_test(); } catch (std::exception& e) { - std::cout << "unexpected exception: " << e.what() << std::endl; + std::cout << "unexpected exception: " << e.what() << '\n'; } return 0; diff --git a/libtests/rc4.cc b/libtests/rc4.cc index 306d088..d540347 100644 --- a/libtests/rc4.cc +++ b/libtests/rc4.cc @@ -20,7 +20,7 @@ other_tests() memcpy(data.get(), "potato", 6); r.process(data.get(), 6, data.get()); assert(memcmp(data.get(), "\xa5\x6f\xe7\x27\x2b\x5c", 6) == 0); - std::cout << "passed" << std::endl; + std::cout << "passed" << '\n'; } int @@ -32,7 +32,7 @@ main(int argc, char* argv[]) } if (argc != 4) { - std::cerr << "Usage: rc4 hex-key infile outfile" << std::endl; + std::cerr << "Usage: rc4 hex-key infile outfile" << '\n'; exit(2); } diff --git a/libtests/runlength.cc b/libtests/runlength.cc index 293aee2..d1b4cfa 100644 --- a/libtests/runlength.cc +++ b/libtests/runlength.cc @@ -11,7 +11,7 @@ int main(int argc, char* argv[]) { if (argc != 4) { - std::cerr << "Usage: runlength {-encode|-decode} infile outfile" << std::endl; + std::cerr << "Usage: runlength {-encode|-decode} infile outfile" << '\n'; exit(2); } diff --git a/libtests/sparse_array.cc b/libtests/sparse_array.cc index 7bbdc23..449cfd8 100644 --- a/libtests/sparse_array.cc +++ b/libtests/sparse_array.cc @@ -118,6 +118,6 @@ main() } catch (std::logic_error&) { } - std::cout << "sparse array tests done" << std::endl; + std::cout << "sparse array tests done" << '\n'; return 0; } diff --git a/qpdf/fix-qdf.cc b/qpdf/fix-qdf.cc index a05a038..087cd20 100644 --- a/qpdf/fix-qdf.cc +++ b/qpdf/fix-qdf.cc @@ -81,7 +81,7 @@ QdfFixer::QdfFixer(std::string const& filename, std::ostream& out) : void QdfFixer::fatal(std::string const& msg) { - std::cerr << msg << std::endl; + std::cerr << msg << '\n'; exit(2); } @@ -380,7 +380,7 @@ realmain(int argc, char* argv[]) if (argc > 3) { usage(); } else if ((argc > 1) && (strcmp(argv[1], "--version") == 0)) { - std::cout << whoami << " from qpdf version " << QPDF::QPDFVersion() << std::endl; + std::cout << whoami << " from qpdf version " << QPDF::QPDFVersion() << '\n'; return 0; } else if ((argc > 1) && (strcmp(argv[1], "--help") == 0)) { usage(); @@ -411,7 +411,7 @@ realmain(int argc, char* argv[]) QdfFixer qf(filename, out ? *out : std::cout); qf.processLines(input); } catch (std::exception& e) { - std::cerr << whoami << ": error: " << e.what() << std::endl; + std::cerr << whoami << ": error: " << e.what() << '\n'; exit(qpdf_exit_error); } return 0; diff --git a/qpdf/pdf_from_scratch.cc b/qpdf/pdf_from_scratch.cc index 2c54d5e..cccc207 100644 --- a/qpdf/pdf_from_scratch.cc +++ b/qpdf/pdf_from_scratch.cc @@ -14,7 +14,7 @@ static char const* whoami = nullptr; void usage() { - std::cerr << "Usage: " << whoami << " n" << std::endl; + std::cerr << "Usage: " << whoami << " n\n"; exit(2); } @@ -77,7 +77,7 @@ runtest(int n) throw std::runtime_error(std::string("invalid test ") + std::to_string(n)); } - std::cout << "test " << n << " done" << std::endl; + std::cout << "test " << n << " done\n"; } int @@ -98,7 +98,7 @@ main(int argc, char* argv[]) int n = QUtil::string_to_int(argv[1]); runtest(n); } catch (std::exception& e) { - std::cerr << e.what() << std::endl; + std::cerr << e.what() << '\n'; exit(2); } diff --git a/qpdf/qpdf.cc b/qpdf/qpdf.cc index dc9c6f2..1f20f10 100644 --- a/qpdf/qpdf.cc +++ b/qpdf/qpdf.cc @@ -11,15 +11,15 @@ static char const* whoami = nullptr; static void usageExit(std::string const& msg) { - std::cerr << std::endl - << whoami << ": " << msg << std::endl - << std::endl - << "For help:" << std::endl - << " " << whoami << " --help=usage usage information" << std::endl - << " " << whoami << " --help=topic help on a topic" << std::endl - << " " << whoami << " --help=--option help on an option" << std::endl - << " " << whoami << " --help general help and a topic list" << std::endl - << std::endl; + std::cerr << '\n' + << whoami << ": " << msg << '\n' + << '\n' + << "For help:\n" + << " " << whoami << " --help=usage usage information\n" + << " " << whoami << " --help=topic help on a topic\n" + << " " << whoami << " --help=--option help on an option\n" + << " " << whoami << " --help general help and a topic list\n" + << '\n'; exit(QPDFJob::EXIT_ERROR); } @@ -37,7 +37,7 @@ realmain(int argc, char* argv[]) } catch (QPDFUsage& e) { usageExit(e.what()); } catch (std::exception& e) { - std::cerr << whoami << ": " << e.what() << std::endl; + std::cerr << whoami << ": " << e.what() << '\n'; return QPDFJob::EXIT_ERROR; } return j.getExitCode(); diff --git a/qpdf/test_driver.cc b/qpdf/test_driver.cc index 4cb8882..b2cb985 100644 --- a/qpdf/test_driver.cc +++ b/qpdf/test_driver.cc @@ -39,7 +39,7 @@ static char const* whoami = nullptr; void usage() { - std::cerr << "Usage: " << whoami << " n filename1 [arg2]" << std::endl; + std::cerr << "Usage: " << whoami << " n filename1 [arg2]" << '\n'; exit(2); } @@ -58,7 +58,7 @@ ExtendNameTree::ExtendNameTree(QPDFObjectHandle o, QPDF& q) : ExtendNameTree::~ExtendNameTree() { - std::cout << "~ExtendNameTree called" << std::endl; + std::cout << "~ExtendNameTree called" << '\n'; } class Provider: public QPDFObjectHandle::StreamDataProvider @@ -104,30 +104,30 @@ class ParserCallbacks: public QPDFObjectHandle::ParserCallbacks void ParserCallbacks::contentSize(size_t size) { - std::cout << "content size: " << size << std::endl; + std::cout << "content size: " << size << '\n'; } void ParserCallbacks::handleObject(QPDFObjectHandle obj, size_t offset, size_t length) { if (obj.isName() && (obj.getName() == "/Abort")) { - std::cout << "test suite: terminating parsing" << std::endl; + std::cout << "test suite: terminating parsing" << '\n'; terminateParsing(); } std::cout << obj.getTypeName() << ", offset=" << offset << ", length=" << length << ": "; if (obj.isInlineImage()) { // Exercise getTypeCode assert(obj.getTypeCode() == ::ot_inlineimage); - std::cout << QUtil::hex_encode(obj.getInlineImageValue()) << std::endl; + std::cout << QUtil::hex_encode(obj.getInlineImageValue()) << '\n'; } else { - std::cout << obj.unparse() << std::endl; + std::cout << obj.unparse() << '\n'; } } void ParserCallbacks::handleEOF() { - std::cout << "-EOF-" << std::endl; + std::cout << "-EOF-" << '\n'; } class TokenFilter: public QPDFObjectHandle::TokenFilter @@ -165,7 +165,7 @@ checkPageContents(QPDFObjectHandle page, std::string const& wanted_string) { std::string contents = getPageContents(page); if (contents.find(wanted_string) == std::string::npos) { - std::cout << "didn't find " << wanted_string << " in " << contents << std::endl; + std::cout << "didn't find " << wanted_string << " in " << contents << '\n'; } } @@ -207,77 +207,77 @@ test_0_1(QPDF& pdf, char const* arg2) // any difference between a key that is present and null // and a key that is absent. QTC::TC("qpdf", "main QTest implicit"); - std::cout << "/QTest is implicit" << std::endl; + std::cout << "/QTest is implicit" << '\n'; } QTC::TC("qpdf", "main QTest indirect", qtest.isIndirect() ? 1 : 0); std::cout << "/QTest is " << (qtest.isIndirect() ? "in" : "") << "direct and has type " - << qtest.getTypeName() << " (" << qtest.getTypeCode() << ")" << std::endl; + << qtest.getTypeName() << " (" << qtest.getTypeCode() << ")" << '\n'; if (qtest.isNull()) { QTC::TC("qpdf", "main QTest null"); - std::cout << "/QTest is null" << std::endl; + std::cout << "/QTest is null" << '\n'; } else if (qtest.isBool()) { QTC::TC("qpdf", "main QTest bool", qtest.getBoolValue() ? 1 : 0); std::cout << "/QTest is Boolean with value " << (qtest.getBoolValue() ? "true" : "false") - << std::endl; + << '\n'; } else if (qtest.isInteger()) { QTC::TC("qpdf", "main QTest int"); - std::cout << "/QTest is an integer with value " << qtest.getIntValue() << std::endl; + std::cout << "/QTest is an integer with value " << qtest.getIntValue() << '\n'; } else if (qtest.isReal()) { QTC::TC("qpdf", "main QTest real"); - std::cout << "/QTest is a real number with value " << qtest.getRealValue() << std::endl; + std::cout << "/QTest is a real number with value " << qtest.getRealValue() << '\n'; } else if (qtest.isName()) { QTC::TC("qpdf", "main QTest name"); - std::cout << "/QTest is a name with value " << qtest.getName() << std::endl; + std::cout << "/QTest is a name with value " << qtest.getName() << '\n'; } else if (qtest.isString()) { QTC::TC("qpdf", "main QTest string"); - std::cout << "/QTest is a string with value " << qtest.getStringValue() << std::endl; + std::cout << "/QTest is a string with value " << qtest.getStringValue() << '\n'; } else if (qtest.isArray()) { QTC::TC("qpdf", "main QTest array"); - std::cout << "/QTest is an array with " << qtest.getArrayNItems() << " items" << std::endl; + std::cout << "/QTest is an array with " << qtest.getArrayNItems() << " items" << '\n'; int i = 0; for (auto& iter: qtest.aitems()) { QTC::TC("qpdf", "main QTest array indirect", iter.isIndirect() ? 1 : 0); std::cout << " item " << i << " is " << (iter.isIndirect() ? "in" : "") << "direct" - << std::endl; + << '\n'; ++i; } } else if (qtest.isDictionary()) { QTC::TC("qpdf", "main QTest dictionary"); - std::cout << "/QTest is a dictionary" << std::endl; + std::cout << "/QTest is a dictionary" << '\n'; for (auto& iter: qtest.ditems()) { QTC::TC("qpdf", "main QTest dictionary indirect", iter.second.isIndirect() ? 1 : 0); std::cout << " " << iter.first << " is " << (iter.second.isIndirect() ? "in" : "") - << "direct" << std::endl; + << "direct" << '\n'; } } else if (qtest.isStream()) { QTC::TC("qpdf", "main QTest stream"); - std::cout << "/QTest is a stream. Dictionary: " << qtest.getDict().unparse() << std::endl; + std::cout << "/QTest is a stream. Dictionary: " << qtest.getDict().unparse() << '\n'; - std::cout << "Raw stream data:" << std::endl; + std::cout << "Raw stream data:" << '\n'; std::cout.flush(); QUtil::binary_stdout(); auto out = std::make_shared("raw", stdout); qtest.pipeStreamData(out.get(), 0, qpdf_dl_none); - std::cout << std::endl << "Uncompressed stream data:" << std::endl; + std::cout << '\n' << "Uncompressed stream data:" << '\n'; if (qtest.pipeStreamData(nullptr, 0, qpdf_dl_all)) { std::cout.flush(); QUtil::binary_stdout(); out = std::make_shared("filtered", stdout); qtest.pipeStreamData(out.get(), 0, qpdf_dl_all); - std::cout << std::endl << "End of stream data" << std::endl; + std::cout << '\n' << "End of stream data" << '\n'; } else { - std::cout << "Stream data is not filterable." << std::endl; + std::cout << "Stream data is not filterable." << '\n'; } } else { // Should not happen! - std::cout << "/QTest is an unknown object" << std::endl; + std::cout << "/QTest is an unknown object" << '\n'; } - std::cout << "unparse: " << qtest.unparse() << std::endl - << "unparseResolved: " << qtest.unparseResolved() << std::endl; + std::cout << "unparse: " << qtest.unparse() << '\n' + << "unparseResolved: " << qtest.unparseResolved() << '\n'; } static void @@ -287,12 +287,12 @@ test_2(QPDF& pdf, char const* arg2) // PDF file. QPDFObjectHandle trailer = pdf.getTrailer(); - std::cout << trailer.getKey("/Info").getKey("/CreationDate").getStringValue() << std::endl; - std::cout << trailer.getKey("/Info").getKey("/Producer").getStringValue() << std::endl; + std::cout << trailer.getKey("/Info").getKey("/CreationDate").getStringValue() << '\n'; + std::cout << trailer.getKey("/Info").getKey("/Producer").getStringValue() << '\n'; QPDFObjectHandle encrypt = trailer.getKey("/Encrypt"); - std::cout << encrypt.getKey("/O").unparse() << std::endl; - std::cout << encrypt.getKey("/U").unparse() << std::endl; + std::cout << encrypt.getKey("/O").unparse() << '\n'; + std::cout << encrypt.getKey("/U").unparse() << '\n'; QPDFObjectHandle root = pdf.getRoot(); QPDFObjectHandle pages = root.getKey("/Pages"); @@ -310,7 +310,7 @@ test_3(QPDF& pdf, char const* arg2) QPDFObjectHandle streams = pdf.getTrailer().getKey("/QStreams"); for (int i = 0; i < streams.getArrayNItems(); ++i) { QPDFObjectHandle stream = streams.getArrayItem(i); - std::cout << "-- stream " << i << " --" << std::endl; + std::cout << "-- stream " << i << " --" << '\n'; std::cout.flush(); QUtil::binary_stdout(); auto out = std::make_shared("tokenized stream", stdout); @@ -374,44 +374,44 @@ test_5(QPDF& pdf, char const* arg2) int pageno = 0; for (auto& page: QPDFPageDocumentHelper(pdf).getAllPages()) { ++pageno; - std::cout << "page " << pageno << ":" << std::endl; - std::cout << " images:" << std::endl; + std::cout << "page " << pageno << ":" << '\n'; + std::cout << " images:" << '\n'; for (auto const& iter2: page.getImages()) { std::string const& name = iter2.first; QPDFObjectHandle image = iter2.second; QPDFObjectHandle dict = image.getDict(); long long width = dict.getKey("/Width").getIntValue(); long long height = dict.getKey("/Height").getIntValue(); - std::cout << " " << name << ": " << width << " x " << height << std::endl; + std::cout << " " << name << ": " << width << " x " << height << '\n'; } - std::cout << " content:" << std::endl; + std::cout << " content:" << '\n'; std::vector content = page.getPageContents(); for (auto& iter2: content) { - std::cout << " " << iter2.unparse() << std::endl; + std::cout << " " << iter2.unparse() << '\n'; } - std::cout << "end page " << pageno << std::endl; + std::cout << "end page " << pageno << '\n'; } QPDFObjectHandle root = pdf.getRoot(); QPDFObjectHandle qstrings = root.getKey("/QStrings"); if (qstrings.isArray()) { - std::cout << "QStrings:" << std::endl; + std::cout << "QStrings:" << '\n'; int nitems = qstrings.getArrayNItems(); for (int i = 0; i < nitems; ++i) { - std::cout << qstrings.getArrayItem(i).getUTF8Value() << std::endl; + std::cout << qstrings.getArrayItem(i).getUTF8Value() << '\n'; } } QPDFObjectHandle qnumbers = root.getKey("/QNumbers"); if (qnumbers.isArray()) { - std::cout << "QNumbers:" << std::endl; + std::cout << "QNumbers:" << '\n'; int nitems = qnumbers.getArrayNItems(); for (int i = 0; i < nitems; ++i) { std::cout << QUtil::double_to_string( qnumbers.getArrayItem(i).getNumericValue(), 3, false) - << std::endl; + << '\n'; } } } @@ -432,7 +432,7 @@ test_6(QPDF& pdf, char const* arg2) cleartext = true; } std::cout << "encrypted=" << (pdf.isEncrypted() ? 1 : 0) - << "; cleartext=" << (cleartext ? 1 : 0) << std::endl; + << "; cleartext=" << (cleartext ? 1 : 0) << '\n'; } static void @@ -483,9 +483,9 @@ test_8(QPDF& pdf, char const* arg2) provider->badLength(true); try { qstream.getStreamData(); - std::cout << "oops -- getStreamData didn't throw" << std::endl; + std::cout << "oops -- getStreamData didn't throw" << '\n'; } catch (std::exception const& e) { - std::cout << "exception: " << e.what() << std::endl; + std::cout << "exception: " << e.what() << '\n'; } } @@ -501,9 +501,9 @@ test_9(QPDF& pdf, char const* arg2) QPDFObjectHandle rstream = QPDFObjectHandle::newStream(&pdf); try { rstream.getStreamData(); - std::cout << "oops -- getStreamData didn't throw" << std::endl; + std::cout << "oops -- getStreamData didn't throw" << '\n'; } catch (std::logic_error const& e) { - std::cout << "exception: " << e.what() << std::endl; + std::cout << "exception: " << e.what() << '\n'; } rstream.replaceStreamData( "data for other stream\n", QPDFObjectHandle::newNull(), QPDFObjectHandle::newNull()); @@ -539,10 +539,10 @@ test_11(QPDF& pdf, char const* arg2) std::shared_ptr b1 = qstream.getStreamData(); std::shared_ptr b2 = qstream.getRawStreamData(); if ((b1->getSize() == 7) && (memcmp(b1->getBuffer(), "potato\n", 7) == 0)) { - std::cout << "filtered stream data okay" << std::endl; + std::cout << "filtered stream data okay" << '\n'; } if ((b2->getSize() == 15) && (memcmp(b2->getBuffer(), "706F7461746F0A\n", 15) == 0)) { - std::cout << "raw stream data okay" << std::endl; + std::cout << "raw stream data okay" << '\n'; } } @@ -580,9 +580,7 @@ test_13(QPDF& pdf, char const* arg2) # pragma GCC diagnostic pop #endif pdf.showLinearizationData(); - std::cout << "---output---" << std::endl - << out.str() << "---error---" << std::endl - << err.str(); + std::cout << "---output---" << '\n' << out.str() << "---error---" << '\n' << err.str(); } static void @@ -614,27 +612,27 @@ test_14(QPDF& pdf, char const* arg2) // Do it wrong first... pdf.replaceObject(qdict.getObjGen(), qdict); } catch (std::logic_error const&) { - std::cout << "caught logic error as expected" << std::endl; + std::cout << "caught logic error as expected" << '\n'; } pdf.replaceObject(qdict.getObjGen(), new_dict); // Now qdict points to the new dictionary - std::cout << "old dict: " << qdict.getKey("/NewDict").getIntValue() << std::endl; + std::cout << "old dict: " << qdict.getKey("/NewDict").getIntValue() << '\n'; // Swap dict and array pdf.swapObjects(qdict.getObjGen(), qarray.getObjGen()); // Now qarray will resolve to new object and qdict resolves to // the array - std::cout << "swapped array: " << qdict.getArrayItem(0).getName() << std::endl; - std::cout << "new dict: " << qarray.getKey("/NewDict").getIntValue() << std::endl; + std::cout << "swapped array: " << qdict.getArrayItem(0).getName() << '\n'; + std::cout << "new dict: " << qarray.getKey("/NewDict").getIntValue() << '\n'; // Reread qdict, still pointing to an array qdict = pdf.getObjectByObjGen(qdict.getObjGen()); - std::cout << "swapped array: " << qdict.getArrayItem(0).getName() << std::endl; + std::cout << "swapped array: " << qdict.getArrayItem(0).getName() << '\n'; // Exercise getAsMap and getAsArray std::vector array_elements = qdict.getArrayAsVector(); std::map dict_items = qarray.getDictAsMap(); if ((array_elements.size() == 1) && (array_elements.at(0).getName() == "/Array") && (dict_items.size() == 1) && (dict_items["/NewDict"].getIntValue() == 2)) { - std::cout << "array and dictionary contents are correct" << std::endl; + std::cout << "array and dictionary contents are correct" << '\n'; } // Exercise writing to memory buffer @@ -853,7 +851,7 @@ test_21(QPDF& pdf, char const* arg2) QPDFObjectHandle page = pages.at(0); QPDFObjectHandle contents = page.getKey("/Contents"); contents.shallowCopy(); - std::cout << "you can't see this" << std::endl; + std::cout << "you can't see this" << '\n'; } static void @@ -865,7 +863,7 @@ test_22(QPDF& pdf, char const* arg2) QPDFPageObjectHelper& page = pages.at(0); dh.removePage(page); dh.removePage(page); - std::cout << "you can't see this" << std::endl; + std::cout << "you can't see this" << '\n'; } static void @@ -895,44 +893,44 @@ test_24(QPDF& pdf, char const* arg2) // Make sure trying to ask questions about a reserved object // doesn't break it. if (res1.isArray()) { - std::cout << "oops -- res1 is an array" << std::endl; + std::cout << "oops -- res1 is an array" << '\n'; } if (res1.isReserved()) { - std::cout << "res1 is still reserved after checking if array" << std::endl; + std::cout << "res1 is still reserved after checking if array" << '\n'; } pdf.replaceReserved(res1, array1); if (res1.isReserved()) { - std::cout << "oops -- res1 is still reserved" << std::endl; + std::cout << "oops -- res1 is still reserved" << '\n'; } else { - std::cout << "res1 is no longer reserved" << std::endl; + std::cout << "res1 is no longer reserved" << '\n'; } res1.assertArray(); - std::cout << "res1 is an array" << std::endl; + std::cout << "res1 is an array" << '\n'; try { res2.unparseResolved(); - std::cout << "oops -- didn't throw" << std::endl; + std::cout << "oops -- didn't throw" << '\n'; } catch (std::logic_error const& e) { - std::cout << "logic error: " << e.what() << std::endl; + std::cout << "logic error: " << e.what() << '\n'; } try { res2.makeDirect(); - std::cout << "oops -- didn't throw" << std::endl; + std::cout << "oops -- didn't throw" << '\n'; } catch (std::logic_error const& e) { - std::cout << "logic error: " << e.what() << std::endl; + std::cout << "logic error: " << e.what() << '\n'; } pdf.replaceReserved(res2, array2); res2.assertArray(); - std::cout << "res2 is an array" << std::endl; + std::cout << "res2 is an array" << '\n'; // Verify that the previously added reserved keys can be // dereferenced properly now int i1 = res1.getArrayItem(0).getArrayItem(1).getIntValueAsInt(); int i2 = res2.getArrayItem(0).getArrayItem(1).getIntValueAsInt(); if ((i1 == 2) && (i2 == 1)) { - std::cout << "circular access and lazy resolution worked" << std::endl; + std::cout << "circular access and lazy resolution worked" << '\n'; } QPDFWriter w(pdf, "a.pdf"); @@ -1078,15 +1076,15 @@ test_28(QPDF& pdf, char const* arg2) // Copy foreign object errors try { pdf.copyForeignObject(pdf.getTrailer().getKey("/QTest")); - std::cout << "oops -- didn't throw" << std::endl; + std::cout << "oops -- didn't throw" << '\n'; } catch (std::logic_error const& e) { - std::cout << "logic error: " << e.what() << std::endl; + std::cout << "logic error: " << e.what() << '\n'; } try { pdf.copyForeignObject(QPDFObjectHandle::newInteger(1)); - std::cout << "oops -- didn't throw" << std::endl; + std::cout << "oops -- didn't throw" << '\n'; } catch (std::logic_error const& e) { - std::cout << "logic error: " << e.what() << std::endl; + std::cout << "logic error: " << e.what() << '\n'; } } @@ -1111,9 +1109,9 @@ test_29(QPDF& pdf, char const* arg2) try { QPDFWriter w(*other, "a.pdf"); w.write(); - std::cout << "oops -- didn't throw" << std::endl; + std::cout << "oops -- didn't throw" << '\n'; } catch (std::logic_error const& e) { - std::cout << "logic error: " << e.what() << std::endl; + std::cout << "logic error: " << e.what() << '\n'; } // Make sure deleting the other source doesn't prevent detection. @@ -1126,9 +1124,9 @@ test_29(QPDF& pdf, char const* arg2) try { QPDFWriter w(*other, "a.pdf"); w.write(); - std::cout << "oops -- didn't throw" << std::endl; + std::cout << "oops -- didn't throw" << '\n'; } catch (std::logic_error const& e) { - std::cout << "logic error: " << e.what() << std::endl; + std::cout << "logic error: " << e.what() << '\n'; } // Detect adding a foreign object @@ -1137,7 +1135,7 @@ test_29(QPDF& pdf, char const* arg2) try { root1.replaceKey("/Oops", root2); } catch (std::logic_error const& e) { - std::cout << "logic error: " << e.what() << std::endl; + std::cout << "logic error: " << e.what() << '\n'; } } @@ -1160,10 +1158,10 @@ test_30(QPDF& pdf, char const* arg2) pages = final.getAllPages(); std::string new_contents = getPageContents(pages.at(0)); if (orig_contents != new_contents) { - std::cout << "oops -- page contents don't match" << std::endl + std::cout << "oops -- page contents don't match" << '\n' << "original:\n" << orig_contents << "new:\n" - << new_contents << std::endl; + << new_contents << '\n'; } } @@ -1172,20 +1170,20 @@ test_31(QPDF& pdf, char const* arg2) { auto o1 = "[/name 16059 3.14159 false\n" " << /key true /other [ (string1) (string2) ] >> null]"_qpdf; - std::cout << o1.unparse() << std::endl; + std::cout << o1.unparse() << '\n'; QPDFObjectHandle o2 = QPDFObjectHandle::parse(" 12345 \f "); assert(o2.isInteger() && (o2.getIntValue() == 12345)); try { QPDFObjectHandle::parse("[1 0 R]", "indirect test"); - std::cout << "oops -- didn't throw" << std::endl; + std::cout << "oops -- didn't throw" << '\n'; } catch (std::logic_error const& e) { - std::cout << "logic error parsing indirect: " << e.what() << std::endl; + std::cout << "logic error parsing indirect: " << e.what() << '\n'; } try { QPDFObjectHandle::parse("0 trailing", "trailing test"); - std::cout << "oops -- didn't throw" << std::endl; + std::cout << "oops -- didn't throw" << '\n'; } catch (std::runtime_error const& e) { - std::cout << "trailing data: " << e.what() << std::endl; + std::cout << "trailing data: " << e.what() << '\n'; } assert(QPDFObjectHandle::parse(&pdf, "[5 0 R]").getArrayItem(0).isInteger()); assert(!QPDFObjectHandle::parse(&pdf, "[5 0 R]").getArrayItem(0).isDirectNull()); @@ -1218,9 +1216,9 @@ test_32(QPDF& pdf, char const* arg2) bool newline = ((i & 2) != 0); QPDFWriter w(pdf, filenames[i]); w.setStaticID(true); - std::cout << "file: " << filenames[i] << std::endl - << "linearized: " << (linearized ? "yes" : "no") << std::endl - << "newline: " << (newline ? "yes" : "no") << std::endl; + std::cout << "file: " << filenames[i] << '\n' + << "linearized: " << (linearized ? "yes" : "no") << '\n' + << "newline: " << (newline ? "yes" : "no") << '\n'; w.setLinearization(linearized); if (linearized) { w.setCompressStreams(false); // avoid dependency on zlib's output @@ -1249,14 +1247,14 @@ static void test_34(QPDF& pdf, char const* arg2) { // Look at Extensions dictionary - std::cout << "version: " << pdf.getPDFVersion() << std::endl - << "extension level: " << pdf.getExtensionLevel() << std::endl - << pdf.getRoot().getKey("/Extensions").unparse() << std::endl; + std::cout << "version: " << pdf.getPDFVersion() << '\n' + << "extension level: " << pdf.getExtensionLevel() << '\n' + << pdf.getRoot().getKey("/Extensions").unparse() << '\n'; auto v = pdf.getVersionAsPDFVersion(); std::string v_string; int extension_level; v.getVersion(v_string, extension_level); - std::cout << "As PDFVersion: " << v_string << "/" << extension_level << std::endl; + std::cout << "As PDFVersion: " << v_string << "/" << extension_level << '\n'; } static void @@ -1350,7 +1348,7 @@ test_38(QPDF& pdf, char const* arg2) // Designed for override-compressed-object.pdf QPDFObjectHandle qtest = pdf.getRoot().getKey("/QTest"); for (int i = 0; i < qtest.getArrayNItems(); ++i) { - std::cout << qtest.getArrayItem(i).unparseResolved() << std::endl; + std::cout << qtest.getArrayItem(i).unparseResolved() << '\n'; } } @@ -1360,13 +1358,13 @@ test_39(QPDF& pdf, char const* arg2) // Display image filter and color set for each image on each page int pageno = 0; for (auto& page: QPDFPageDocumentHelper(pdf).getAllPages()) { - std::cout << "page " << ++pageno << std::endl; + std::cout << "page " << ++pageno << '\n'; std::map images = page.getImages(); for (auto& i_iter: images) { QPDFObjectHandle image_dict = i_iter.second.getDict(); std::cout << "filter: " << image_dict.getKey("/Filter").unparseResolved() << ", color space: " << image_dict.getKey("/ColorSpace").unparseResolved() - << std::endl; + << '\n'; } } } @@ -1442,7 +1440,7 @@ test_42(QPDF& pdf, char const* arg2) assert(i == di.end()); assert(!i_value.second); } - assert("" == qtest.getStringValue()); + assert(qtest.getStringValue().empty()); array.getArrayItem(-1).assertNull(); array.getArrayItem(16059).assertNull(); integer.getArrayItem(0).assertNull(); @@ -1578,51 +1576,51 @@ test_43(QPDF& pdf, char const* arg2) } std::cout << "iterating over form fields\n"; for (auto& ffh: afdh.getFormFields()) { - std::cout << "Field: " << ffh.getObjectHandle().unparse() << std::endl; + std::cout << "Field: " << ffh.getObjectHandle().unparse() << '\n'; QPDFFormFieldObjectHelper node = ffh; while (!node.isNull()) { QPDFFormFieldObjectHelper parent(node.getParent()); std::cout << " Parent: " << (parent.isNull() ? std::string("none") : parent.getObjectHandle().unparse()) - << std::endl; + << '\n'; node = parent; } - std::cout << " Fully qualified name: " << ffh.getFullyQualifiedName() << std::endl; - std::cout << " Partial name: " << ffh.getPartialName() << std::endl; - std::cout << " Alternative name: " << ffh.getAlternativeName() << std::endl; - std::cout << " Mapping name: " << ffh.getMappingName() << std::endl; - std::cout << " Field type: " << ffh.getFieldType() << std::endl; - std::cout << " Value: " << ffh.getValue().unparse() << std::endl; - std::cout << " Value as string: " << ffh.getValueAsString() << std::endl; - std::cout << " Default value: " << ffh.getDefaultValue().unparse() << std::endl; - std::cout << " Default value as string: " << ffh.getDefaultValueAsString() << std::endl; - std::cout << " Default appearance: " << ffh.getDefaultAppearance() << std::endl; - std::cout << " Quadding: " << ffh.getQuadding() << std::endl; + std::cout << " Fully qualified name: " << ffh.getFullyQualifiedName() << '\n'; + std::cout << " Partial name: " << ffh.getPartialName() << '\n'; + std::cout << " Alternative name: " << ffh.getAlternativeName() << '\n'; + std::cout << " Mapping name: " << ffh.getMappingName() << '\n'; + std::cout << " Field type: " << ffh.getFieldType() << '\n'; + std::cout << " Value: " << ffh.getValue().unparse() << '\n'; + std::cout << " Value as string: " << ffh.getValueAsString() << '\n'; + std::cout << " Default value: " << ffh.getDefaultValue().unparse() << '\n'; + std::cout << " Default value as string: " << ffh.getDefaultValueAsString() << '\n'; + std::cout << " Default appearance: " << ffh.getDefaultAppearance() << '\n'; + std::cout << " Quadding: " << ffh.getQuadding() << '\n'; std::vector annotations = afdh.getAnnotationsForField(ffh); for (auto& aoh: annotations) { - std::cout << " Annotation: " << aoh.getObjectHandle().unparse() << std::endl; + std::cout << " Annotation: " << aoh.getObjectHandle().unparse() << '\n'; } } std::cout << "iterating over annotations per page\n"; for (auto& page: QPDFPageDocumentHelper(pdf).getAllPages()) { - std::cout << "Page: " << page.getObjectHandle().unparse() << std::endl; + std::cout << "Page: " << page.getObjectHandle().unparse() << '\n'; for (auto& ah: afdh.getWidgetAnnotationsForPage(page)) { - std::cout << " Annotation: " << ah.getObjectHandle().unparse() << std::endl; + std::cout << " Annotation: " << ah.getObjectHandle().unparse() << '\n'; std::cout << " Field: " - << (afdh.getFieldForAnnotation(ah).getObjectHandle().unparse()) << std::endl; - std::cout << " Subtype: " << ah.getSubtype() << std::endl; + << (afdh.getFieldForAnnotation(ah).getObjectHandle().unparse()) << '\n'; + std::cout << " Subtype: " << ah.getSubtype() << '\n'; std::cout << " Rect: "; print_rect(std::cout, ah.getRect()); - std::cout << std::endl; + std::cout << '\n'; std::string state = ah.getAppearanceState(); if (!state.empty()) { - std::cout << " Appearance state: " << state << std::endl; + std::cout << " Appearance state: " << state << '\n'; } std::cout << " Appearance stream (/N): " << ah.getAppearanceStream("/N").unparse() - << std::endl; + << '\n'; std::cout << " Appearance stream (/N, /3): " - << ah.getAppearanceStream("/N", "/3").unparse() << std::endl; + << ah.getAppearanceStream("/N", "/3").unparse() << '\n'; } } } @@ -1637,7 +1635,7 @@ test_44(QPDF& pdf, char const* arg2) // \xc3\xb7 is utf-8 for U+00F7 (divided by) field.setV("3.14 \xc3\xb7 0"); std::cout << "Set field value: " << field.getFullyQualifiedName() << " -> " - << field.getValueAsString() << std::endl; + << field.getValueAsString() << '\n'; } } QPDFWriter w(pdf, "a.pdf"); @@ -1669,11 +1667,11 @@ test_46(QPDF& pdf, char const* arg2) QPDFObjectHandle qtest = pdf.getTrailer().getKey("/QTest"); QPDFNumberTreeObjectHelper ntoh(qtest, pdf); for (auto& iter: ntoh) { - std::cout << iter.first << " " << iter.second.getStringValue() << std::endl; + std::cout << iter.first << " " << iter.second.getStringValue() << '\n'; } QPDFNumberTreeObjectHelper::idx_map ntoh_map = ntoh.getAsMap(); for (auto& iter: ntoh_map) { - std::cout << iter.first << " " << iter.second.getStringValue() << std::endl; + std::cout << iter.first << " " << iter.second.getStringValue() << '\n'; } assert(1 == ntoh.getMin()); assert(29 == ntoh.getMax()); @@ -1719,7 +1717,7 @@ test_46(QPDF& pdf, char const* arg2) --iter1; assert(iter1->first == 2); - std::cout << "insertAfter" << std::endl; + std::cout << "insertAfter" << '\n'; auto new2 = QPDFNumberTreeObjectHelper::newEmpty(pdf); auto iter2 = new2.begin(); assert(iter2 == new2.end()); @@ -1728,23 +1726,23 @@ test_46(QPDF& pdf, char const* arg2) iter2.insertAfter(4, QPDFObjectHandle::newString("4!")); assert(iter2->first == 4); for (auto& i: new2) { - std::cout << i.first << " " << i.second.unparse() << std::endl; + std::cout << i.first << " " << i.second.unparse() << '\n'; } - std::cout << "/Bad1" << std::endl; + std::cout << "/Bad1" << '\n'; auto bad1 = QPDFNumberTreeObjectHelper(pdf.getTrailer().getKey("/Bad1"), pdf); assert(bad1.begin() == bad1.end()); assert(bad1.last() == bad1.end()); - std::cout << "/Bad2" << std::endl; + std::cout << "/Bad2" << '\n'; auto bad2 = QPDFNumberTreeObjectHelper(pdf.getTrailer().getKey("/Bad2"), pdf); for (auto& i: bad2) { - std::cout << i.first << " " << i.second.unparse() << std::endl; + std::cout << i.first << " " << i.second.unparse() << '\n'; } std::vector empties = {"/Empty1", "/Empty2"}; for (auto const& k: empties) { - std::cout << k << std::endl; + std::cout << k << '\n'; auto empty = QPDFNumberTreeObjectHelper(pdf.getTrailer().getKey(k), pdf); assert(empty.begin() == empty.end()); assert(empty.last() == empty.end()); @@ -1765,37 +1763,37 @@ test_46(QPDF& pdf, char const* arg2) assert(empty.last()->first == 6); assert(empty.last()->second.getStringValue() == "6"); } - std::cout << "Insert into invalid" << std::endl; + std::cout << "Insert into invalid" << '\n'; auto invalid1 = QPDFNumberTreeObjectHelper(QPDFObjectHandle::newDictionary(), pdf); try { invalid1.insert(1, QPDFObjectHandle::newNull()); } catch (QPDFExc& e) { - std::cout << e.what() << std::endl; + std::cout << e.what() << '\n'; } - std::cout << "/Bad3, no repair" << std::endl; + std::cout << "/Bad3, no repair" << '\n'; auto bad3_oh = pdf.getTrailer().getKey("/Bad3"); auto bad3 = QPDFNumberTreeObjectHelper(bad3_oh, pdf, false); for (auto& i: bad3) { - std::cout << i.first << " " << i.second.unparse() << std::endl; + std::cout << i.first << " " << i.second.unparse() << '\n'; } assert(!bad3_oh.getKey("/Kids").getArrayItem(0).isIndirect()); - std::cout << "/Bad3, repair" << std::endl; + std::cout << "/Bad3, repair" << '\n'; bad3 = QPDFNumberTreeObjectHelper(bad3_oh, pdf, true); for (auto& i: bad3) { - std::cout << i.first << " " << i.second.unparse() << std::endl; + std::cout << i.first << " " << i.second.unparse() << '\n'; } assert(bad3_oh.getKey("/Kids").getArrayItem(0).isIndirect()); - std::cout << "/Bad4 -- missing limits" << std::endl; + std::cout << "/Bad4 -- missing limits" << '\n'; auto bad4 = QPDFNumberTreeObjectHelper(pdf.getTrailer().getKey("/Bad4"), pdf); bad4.insert(5, QPDFObjectHandle::newString("5")); for (auto& i: bad4) { - std::cout << i.first << " " << i.second.unparse() << std::endl; + std::cout << i.first << " " << i.second.unparse() << '\n'; } - std::cout << "/Bad5 -- limit errors" << std::endl; + std::cout << "/Bad5 -- limit errors" << '\n'; auto bad5 = QPDFNumberTreeObjectHelper(pdf.getTrailer().getKey("/Bad5"), pdf); assert(bad5.find(10) == bad5.end()); } @@ -1810,7 +1808,7 @@ test_47(QPDF& pdf, char const* arg2) pldh.getLabelsForPageRange(0, npages - 1, 1, labels); assert(labels.size() % 2 == 0); for (size_t i = 0; i < labels.size(); i += 2) { - std::cout << labels.at(i).getIntValue() << " " << labels.at(i + 1).unparse() << std::endl; + std::cout << labels.at(i).getIntValue() << " " << labels.at(i + 1).unparse() << '\n'; } } @@ -1822,11 +1820,11 @@ test_48(QPDF& pdf, char const* arg2) QPDFObjectHandle qtest = pdf.getTrailer().getKey("/QTest"); QPDFNameTreeObjectHelper ntoh(qtest, pdf); for (auto& iter: ntoh) { - std::cout << iter.first << " -> " << iter.second.getStringValue() << std::endl; + std::cout << iter.first << " -> " << iter.second.getStringValue() << '\n'; } std::map ntoh_map = ntoh.getAsMap(); for (auto& iter: ntoh_map) { - std::cout << iter.first << " -> " << iter.second.getStringValue() << std::endl; + std::cout << iter.first << " -> " << iter.second.getStringValue() << '\n'; } assert(ntoh.hasName("11 elephant")); assert(ntoh.hasName("07 sev\xe2\x80\xa2n")); @@ -1869,7 +1867,7 @@ test_48(QPDF& pdf, char const* arg2) --iter1; assert(iter1->first == "2"); - std::cout << "insertAfter" << std::endl; + std::cout << "insertAfter" << '\n'; auto new2 = QPDFNameTreeObjectHelper::newEmpty(pdf); auto iter2 = new2.begin(); assert(iter2 == new2.end()); @@ -1878,12 +1876,12 @@ test_48(QPDF& pdf, char const* arg2) iter2.insertAfter("4", QPDFObjectHandle::newString("4!")); assert(iter2->first == "4"); for (auto& i: new2) { - std::cout << i.first << " " << i.second.unparse() << std::endl; + std::cout << i.first << " " << i.second.unparse() << '\n'; } std::vector empties = {"/Empty1", "/Empty2"}; for (auto const& k: empties) { - std::cout << k << std::endl; + std::cout << k << '\n'; auto empty = QPDFNameTreeObjectHelper(pdf.getTrailer().getKey(k), pdf); assert(empty.begin() == empty.end()); assert(empty.last() == empty.end()); @@ -1905,36 +1903,36 @@ test_48(QPDF& pdf, char const* arg2) assert(empty.last()->second.getStringValue() == "6"); } - std::cout << "/Bad1 -- wrong key type" << std::endl; + std::cout << "/Bad1 -- wrong key type" << '\n'; auto bad1 = QPDFNameTreeObjectHelper(pdf.getTrailer().getKey("/Bad1"), pdf); assert(bad1.find("G", true)->first == "A"); for (auto const& i: bad1) { - std::cout << i.first << std::endl; + std::cout << i.first << '\n'; } - std::cout << "/Bad2 -- invalid kid" << std::endl; + std::cout << "/Bad2 -- invalid kid" << '\n'; auto bad2 = QPDFNameTreeObjectHelper(pdf.getTrailer().getKey("/Bad2"), pdf); assert(bad2.find("G", true)->first == "B"); for (auto const& i: bad2) { - std::cout << i.first << std::endl; + std::cout << i.first << '\n'; } - std::cout << "/Bad3 -- invalid kid" << std::endl; + std::cout << "/Bad3 -- invalid kid" << '\n'; auto bad3 = QPDFNameTreeObjectHelper(pdf.getTrailer().getKey("/Bad3"), pdf); assert(bad3.find("G", true) == bad3.end()); - std::cout << "/Bad4 -- invalid kid" << std::endl; + std::cout << "/Bad4 -- invalid kid" << '\n'; auto bad4 = QPDFNameTreeObjectHelper(pdf.getTrailer().getKey("/Bad4"), pdf); assert(bad4.find("F", true)->first == "C"); for (auto const& i: bad4) { - std::cout << i.first << std::endl; + std::cout << i.first << '\n'; } - std::cout << "/Bad5 -- loop in find" << std::endl; + std::cout << "/Bad5 -- loop in find" << '\n'; auto bad5 = QPDFNameTreeObjectHelper(pdf.getTrailer().getKey("/Bad5"), pdf); assert(bad5.find("F", true)->first == "D"); - std::cout << "/Bad6 -- bad limits" << std::endl; + std::cout << "/Bad6 -- bad limits" << '\n'; auto bad6 = QPDFNameTreeObjectHelper(pdf.getTrailer().getKey("/Bad6"), pdf); assert(bad6.insert("H", QPDFObjectHandle::newNull())->first == "H"); } @@ -1949,7 +1947,7 @@ test_49(QPDF& pdf, char const* arg2) auto outlines = odh.getOutlinesForPage(page.getObjectHandle().getObjGen()); for (auto& ol: outlines) { std::cout << "page " << pageno << ": " << ol.getTitle() << " -> " - << ol.getDest().unparseResolved() << std::endl; + << ol.getDest().unparseResolved() << '\n'; } ++pageno; } @@ -1963,11 +1961,11 @@ test_50(QPDF& pdf, char const* arg2) QPDFObjectHandle d1 = pdf.getTrailer().getKey("/Dict1"); QPDFObjectHandle d2 = pdf.getTrailer().getKey("/Dict2"); d1.mergeResources(d2); - std::cout << d1.getJSON(JSON::LATEST).unparse() << std::endl; + std::cout << d1.getJSON(JSON::LATEST).unparse() << '\n'; // Top-level type mismatch d1.mergeResources(d2.getKey("/k1")); for (auto const& name: d1.getResourceNames()) { - std::cout << name << std::endl; + std::cout << name << '\n'; } } @@ -2047,10 +2045,10 @@ test_53(QPDF& pdf, char const* arg2) QPDFObjectHandle root = pdf.getRoot(); auto new_obj = pdf.makeIndirectObject(QPDFObjectHandle::newString("potato")); root.replaceKey("/Q1", new_obj); - std::cout << "new object: " << new_obj.unparse() << std::endl; - std::cout << "all objects" << std::endl; + std::cout << "new object: " << new_obj.unparse() << '\n'; + std::cout << "all objects" << '\n'; for (auto& obj: pdf.getAllObjects()) { - std::cout << obj.unparse() << std::endl; + std::cout << obj.unparse() << '\n'; } QPDFWriter w(pdf, "a.pdf"); @@ -2068,7 +2066,7 @@ test_54(QPDF& pdf, char const* arg2) assert(pdf.getPDFVersion() != "1.5"); w.setObjectStreamMode(qpdf_o_generate); if (w.getFinalVersion() != "1.5") { - std::cout << "oops: " << w.getFinalVersion() << std::endl; + std::cout << "oops: " << w.getFinalVersion() << '\n'; } } @@ -2193,11 +2191,11 @@ test_60(QPDF& pdf, char const* arg2) std::map> conflicts; auto show_conflicts = [&](std::string const& msg) { - std::cout << msg << std::endl; + std::cout << msg << '\n'; for (auto const& i1: conflicts) { - std::cout << i1.first << ":" << std::endl; + std::cout << i1.first << ":" << '\n'; for (auto const& i2: i1.second) { - std::cout << " " << i2.first << " -> " << i2.second << std::endl; + std::cout << " " << i2.first << " -> " << i2.second << '\n'; } } }; @@ -2242,22 +2240,22 @@ test_61(QPDF& pdf, char const* arg2) try { pdf.processMemoryFile("empty", "", 0); } catch (QPDFExc const&) { - std::cout << "Caught QPDFExc as expected" << std::endl; + std::cout << "Caught QPDFExc as expected" << '\n'; } try { QUtil::safe_fopen("/does/not/exist", "r"); } catch (QPDFSystemError const&) { - std::cout << "Caught QPDFSystemError as expected" << std::endl; + std::cout << "Caught QPDFSystemError as expected" << '\n'; } try { QUtil::int_to_string_base(0, 12); } catch (std::logic_error const&) { - std::cout << "Caught logic_error as expected" << std::endl; + std::cout << "Caught logic_error as expected" << '\n'; } try { QUtil::toUTF8(0xffffffff); } catch (std::runtime_error const&) { - std::cout << "Caught runtime_error as expected" << std::endl; + std::cout << "Caught runtime_error as expected" << '\n'; } // Spot check RTTI for dynamic cast. We intend to have pipelines @@ -2389,18 +2387,18 @@ test_68(QPDF& pdf, char const* arg2) QPDFObjectHandle qstream = root.getKey("/QStream"); try { qstream.getStreamData(); - std::cout << "oops -- didn't throw" << std::endl; + std::cout << "oops -- didn't throw" << '\n'; } catch (std::exception& e) { - std::cout << "get unfilterable stream: " << e.what() << std::endl; + std::cout << "get unfilterable stream: " << e.what() << '\n'; } std::shared_ptr b1 = qstream.getStreamData(qpdf_dl_all); if ((b1->getSize() > 10) && (memcmp(b1->getBuffer(), "wwwwwwwww", 9) == 0)) { - std::cout << "filtered stream data okay" << std::endl; + std::cout << "filtered stream data okay" << '\n'; } std::shared_ptr b2 = qstream.getRawStreamData(); if ((b2->getSize() > 10) && (memcmp(b2->getBuffer(), "\xff\xd8\xff\xe0\x00\x10\x4a\x46\x49\x46", 10) == 0)) { - std::cout << "raw stream data okay" << std::endl; + std::cout << "raw stream data okay" << '\n'; } } @@ -2436,42 +2434,42 @@ static void test_71(QPDF& pdf, char const* arg2) { auto show = [](QPDFObjectHandle& obj, QPDFObjectHandle& xobj_dict, std::string const& key) { - std::cout << xobj_dict.unparse() << " -> " << key << " -> " << obj.unparse() << std::endl; + std::cout << xobj_dict.unparse() << " -> " << key << " -> " << obj.unparse() << '\n'; }; auto page = QPDFPageDocumentHelper(pdf).getAllPages().at(0); - std::cout << "--- recursive, all ---" << std::endl; + std::cout << "--- recursive, all ---" << '\n'; page.forEachXObject(true, show); - std::cout << "--- non-recursive, all ---" << std::endl; + std::cout << "--- non-recursive, all ---" << '\n'; page.forEachXObject(false, show); - std::cout << "--- recursive, images ---" << std::endl; + std::cout << "--- recursive, images ---" << '\n'; page.forEachImage(true, show); - std::cout << "--- non-recursive, images ---" << std::endl; + std::cout << "--- non-recursive, images ---" << '\n'; page.forEachImage(false, show); - std::cout << "--- recursive, form XObjects ---" << std::endl; + std::cout << "--- recursive, form XObjects ---" << '\n'; page.forEachFormXObject(true, show); - std::cout << "--- non-recursive, form XObjects ---" << std::endl; + std::cout << "--- non-recursive, form XObjects ---" << '\n'; page.forEachFormXObject(false, show); auto fx1 = QPDFPageObjectHelper( page.getObjectHandle().getKey("/Resources").getKey("/XObject").getKey("/Fx1")); - std::cout << "--- recursive, all, from fx1 ---" << std::endl; + std::cout << "--- recursive, all, from fx1 ---" << '\n'; fx1.forEachXObject(true, show); - std::cout << "--- non-recursive, all, from fx1 ---" << std::endl; + std::cout << "--- non-recursive, all, from fx1 ---" << '\n'; fx1.forEachXObject(false, show); - std::cout << "--- get images, page ---" << std::endl; + std::cout << "--- get images, page ---" << '\n'; for (auto& i: page.getImages()) { - std::cout << i.first << " -> " << i.second.unparse() << std::endl; + std::cout << i.first << " -> " << i.second.unparse() << '\n'; } - std::cout << "--- get images, fx ---" << std::endl; + std::cout << "--- get images, fx ---" << '\n'; for (auto& i: fx1.getImages()) { - std::cout << i.first << " -> " << i.second.unparse() << std::endl; + std::cout << i.first << " -> " << i.second.unparse() << '\n'; } - std::cout << "--- get form XObjects, page ---" << std::endl; + std::cout << "--- get form XObjects, page ---" << '\n'; for (auto& i: page.getFormXObjects()) { - std::cout << i.first << " -> " << i.second.unparse() << std::endl; + std::cout << i.first << " -> " << i.second.unparse() << '\n'; } - std::cout << "--- get form XObjects, fx ---" << std::endl; + std::cout << "--- get form XObjects, fx ---" << '\n'; for (auto& i: fx1.getFormXObjects()) { - std::cout << i.first << " -> " << i.second.unparse() << std::endl; + std::cout << i.first << " -> " << i.second.unparse() << '\n'; } } @@ -2482,7 +2480,7 @@ test_72(QPDF& pdf, char const* arg2) auto page = QPDFPageDocumentHelper(pdf).getAllPages().at(0); auto fx1 = QPDFPageObjectHelper( page.getObjectHandle().getKey("/Resources").getKey("/XObject").getKey("/Fx1")); - std::cout << "--- parseContents ---" << std::endl; + std::cout << "--- parseContents ---" << '\n'; ParserCallbacks cb; fx1.parseContents(&cb); // Do this once with addContentTokenFilter and once with @@ -2511,7 +2509,7 @@ test_73(QPDF& pdf, char const* arg2) QPDF pdf2; pdf2.getRoot(); } catch (std::exception& e) { - std::cerr << "getRoot: " << e.what() << std::endl; + std::cerr << "getRoot: " << e.what() << '\n'; } pdf.closeInputSource(); @@ -2522,7 +2520,7 @@ static void test_74(QPDF& pdf, char const* arg2) { // This test is crafted to work with split-nntree.pdf - std::cout << "/Split1" << std::endl; + std::cout << "/Split1" << '\n'; auto split1 = QPDFNumberTreeObjectHelper(pdf.getTrailer().getKey("/Split1"), pdf); split1.setSplitThreshold(4); auto check_split1 = [&split1](int k) { @@ -2533,10 +2531,10 @@ test_74(QPDF& pdf, char const* arg2) check_split1(35); check_split1(125); for (auto const& i: split1) { - std::cout << i.first << std::endl; + std::cout << i.first << '\n'; } - std::cout << "/Split2" << std::endl; + std::cout << "/Split2" << '\n'; auto split2 = QPDFNameTreeObjectHelper(pdf.getTrailer().getKey("/Split2"), pdf); split2.setSplitThreshold(4); auto check_split2 = [](QPDFNameTreeObjectHelper& noh, std::string const& k) { @@ -2545,16 +2543,16 @@ test_74(QPDF& pdf, char const* arg2) }; check_split2(split2, "C"); for (auto const& i: split2) { - std::cout << i.first << std::endl; + std::cout << i.first << '\n'; } - std::cout << "/Split3" << std::endl; + std::cout << "/Split3" << '\n'; auto split3 = QPDFNameTreeObjectHelper(pdf.getTrailer().getKey("/Split3"), pdf); split3.setSplitThreshold(4); check_split2(split3, "P"); check_split2(split3, "\xcf\x80"); for (auto& i: split3) { - std::cout << i.first << " " << i.second.unparse() << std::endl; + std::cout << i.first << " " << i.second.unparse() << '\n'; } QPDFWriter w(pdf, "a.pdf"); @@ -2655,7 +2653,7 @@ test_76(QPDF& pdf, char const* arg2) assert(QUtil::hex_encode(efs2.getChecksum()) == "2fce9c8228e360ba9b04a1bd1bf63d6b"); for (auto const& iter: efdh.getEmbeddedFiles()) { - std::cout << iter.first << " -> " << iter.second->getFilename() << std::endl; + std::cout << iter.first << " -> " << iter.second->getFilename() << '\n'; } assert(efdh.getEmbeddedFile("att1")->getFilename() == "att1.txt"); assert(!efdh.getEmbeddedFile("potato")); @@ -2689,17 +2687,17 @@ test_78(QPDF& pdf, char const* arg2) p->finish(); }; auto f2 = [](Pipeline* p, bool suppress_warnings, bool will_retry) { - std::cerr << "f2" << std::endl; + std::cerr << "f2" << '\n'; if (will_retry) { - std::cerr << "failing" << std::endl; + std::cerr << "failing" << '\n'; return false; } if (!suppress_warnings) { - std::cerr << "warning" << std::endl; + std::cerr << "warning" << '\n'; } p->writeCStr("salad"); p->finish(); - std::cerr << "f2 done" << std::endl; + std::cerr << "f2 done" << '\n'; return true; }; @@ -2709,11 +2707,11 @@ test_78(QPDF& pdf, char const* arg2) auto s2 = QPDFObjectHandle::newStream(&pdf); s2.replaceStreamData(f2, null, null); pdf.getTrailer().replaceKey("/Streams", QPDFObjectHandle::newArray({s1, s2})); - std::cout << "piping with warning suppression" << std::endl; + std::cout << "piping with warning suppression" << '\n'; Pl_Discard d; s2.pipeStreamData(&d, nullptr, 0, qpdf_dl_all, true, false); - std::cout << "writing" << std::endl; + std::cout << "writing" << '\n'; QPDFWriter w(pdf, "a.pdf"); w.setStaticID(true); w.setQDFMode(true); @@ -2890,13 +2888,13 @@ test_83(QPDF& pdf, char const* arg2) size_t size; QUtil::read_file_into_memory(arg2, file_buf, size); try { - std::cout << "calling initializeFromJson" << std::endl; + std::cout << "calling initializeFromJson" << '\n'; j.initializeFromJson(std::string(file_buf.get(), size)); - std::cout << "called initializeFromJson" << std::endl; + std::cout << "called initializeFromJson" << '\n'; } catch (QPDFUsage& e) { - std::cerr << "usage: " << e.what() << std::endl; + std::cerr << "usage: " << e.what() << '\n'; } catch (std::exception& e) { - std::cerr << "exception: " << e.what() << std::endl; + std::cerr << "exception: " << e.what() << '\n'; } } @@ -2905,7 +2903,7 @@ test_84(QPDF& pdf, char const* arg2) { // Test QPDFJob API - std::cout << "normal" << std::endl; + std::cout << "normal" << '\n'; { QPDFJob j; j.config() @@ -2922,11 +2920,11 @@ test_84(QPDF& pdf, char const* arg2) assert(j.getEncryptionStatus() == 0); } - std::cout << "custom progress reporter" << std::endl; + std::cout << "custom progress reporter" << '\n'; { QPDFJob j; j.registerProgressReporter( - [](int p) { std::cout << "custom write progress: " << p << "%" << std::endl; }); + [](int p) { std::cout << "custom write progress: " << p << "%" << '\n'; }); j.config() ->inputFile("minimal.pdf") ->outputFile("a.pdf") @@ -2941,29 +2939,29 @@ test_84(QPDF& pdf, char const* arg2) assert(j.getEncryptionStatus() == 0); } - std::cout << "error caught by check" << std::endl; + std::cout << "error caught by check" << '\n'; try { QPDFJob j; j.config()->outputFile("a.pdf")->qdf(); - std::cout << "finished config" << std::endl; + std::cout << "finished config" << '\n'; j.checkConfiguration(); assert(false); } catch (QPDFUsage& e) { - std::cout << "usage: " << e.what() << std::endl; + std::cout << "usage: " << e.what() << '\n'; } - std::cout << "error caught by run" << std::endl; + std::cout << "error caught by run" << '\n'; try { QPDFJob j; j.config()->outputFile("a.pdf")->qdf(); - std::cout << "finished config" << std::endl; + std::cout << "finished config" << '\n'; j.run(); assert(false); } catch (QPDFUsage& e) { - std::cout << "usage: " << e.what() << std::endl; + std::cout << "usage: " << e.what() << '\n'; } - std::cout << "output capture" << std::endl; + std::cout << "output capture" << '\n'; std::ostringstream cout; std::ostringstream cerr; { @@ -2980,11 +2978,11 @@ test_84(QPDF& pdf, char const* arg2) # pragma GCC diagnostic pop #endif j.config()->inputFile("bad2.pdf")->showObject("4,0")->checkConfiguration(); - std::cout << "calling run" << std::endl; + std::cout << "calling run" << '\n'; j.run(); - std::cout << "captured stdout" << std::endl; + std::cout << "captured stdout" << '\n'; std::cout << cout.str(); - std::cout << "captured stderr" << std::endl; + std::cout << "captured stderr" << '\n'; std::cout << cerr.str(); } } @@ -3111,7 +3109,7 @@ test_87(QPDF& pdf, char const* arg2) assert(dict.getKeys() == std::set({"/A"})); dict.replaceKey("/A", QPDFObjectHandle::newNull()); assert(dict.unparse() == "<< >>"); - assert(dict.getKeys() == std::set()); + assert(dict.getKeys().empty()); dict = QPDFObjectHandle::newDictionary({ {"/A", "2"_qpdf}, {"/B", QPDFObjectHandle::newNull()}, @@ -3478,7 +3476,7 @@ test_99(QPDF& pdf, char const* arg2) // Designed for no-space-compressed-object.pdf QPDFObjectHandle qtest = pdf.getRoot().getKey("/QTest"); for (int i = 0; i < qtest.getArrayNItems(); ++i) { - std::cout << qtest.getArrayItem(i).unparseResolved() << std::endl; + std::cout << qtest.getArrayItem(i).unparseResolved() << '\n'; } } @@ -3621,7 +3619,7 @@ runtest(int n, char const* filename1, char const* arg2) p[i] = static_cast(p[i] ^ 0xcc); } pdf.processMemoryFile((std::string(filename1) + ".pdf").c_str(), p, size); - } else if (ignore_filename.count(n)) { + } else if (ignore_filename.contains(n)) { // Ignore filename argument entirely } else if (n == 89) { pdf.createFromJSON(filename1); @@ -3669,7 +3667,7 @@ runtest(int n, char const* filename1, char const* arg2) if (filep) { fclose(filep); } - std::cout << "test " << n << " done" << std::endl; + std::cout << "test " << n << " done" << '\n'; } int @@ -3692,7 +3690,7 @@ main(int argc, char* argv[]) char const* arg2 = argv[3]; runtest(n, filename1, arg2); } catch (std::exception& e) { - std::cerr << e.what() << std::endl; + std::cerr << e.what() << '\n'; exit(2); } diff --git a/qpdf/test_large_file.cc b/qpdf/test_large_file.cc index f273c78..cffd526 100644 --- a/qpdf/test_large_file.cc +++ b/qpdf/test_large_file.cc @@ -94,7 +94,7 @@ void ImageChecker::finish() { if (!okay) { - std::cout << "errors found checking image data for page " << n << std::endl; + std::cout << "errors found checking image data for page " << n << '\n'; } } @@ -120,7 +120,7 @@ ImageProvider::provideStreamData(int objid, int generation, Pipeline* pipeline) if (buf == nullptr) { buf = new unsigned char[width * stripesize]; } - std::cout << "page " << n << " of " << npages << std::endl; + std::cout << "page " << n << " of " << npages << '\n'; for (size_t y = 0; y < nstripes; ++y) { unsigned char color = get_pixel_color(n, y); memset(buf, color, width * stripesize); @@ -132,7 +132,7 @@ ImageProvider::provideStreamData(int objid, int generation, Pipeline* pipeline) void usage() { - std::cerr << "Usage: " << whoami << " {read|write} {large|small} outfile" << std::endl; + std::cerr << "Usage: " << whoami << " {read|write} {large|small} outfile" << '\n'; exit(2); } @@ -247,7 +247,7 @@ check_page_contents(size_t pageno, QPDFObjectHandle page) std::string(reinterpret_cast(buf->getBuffer()), buf->getSize()); std::string expected_contents = generate_page_contents(pageno); if (expected_contents != actual_contents) { - std::cout << "page contents wrong for page " << pageno << std::endl + std::cout << "page contents wrong for page " << pageno << '\n' << "ACTUAL: " << actual_contents << "EXPECTED: " << expected_contents << "----\n"; } } @@ -269,7 +269,7 @@ check_pdf(char const* filename) assert(pages.size() == QIntC::to_size(npages)); for (size_t i = 0; i < npages; ++i) { size_t pageno = i + 1; - std::cout << "page " << pageno << " of " << npages << std::endl; + std::cout << "page " << pageno << " of " << npages << '\n'; check_page_contents(pageno, pages.at(i)); check_image(pageno, pages.at(i)); } @@ -316,7 +316,7 @@ main(int argc, char* argv[]) check_pdf(filename); } } catch (std::exception& e) { - std::cerr << e.what() << std::endl; + std::cerr << e.what() << '\n'; exit(2); } diff --git a/qpdf/test_many_nulls.cc b/qpdf/test_many_nulls.cc index 07e81af..84677d1 100644 --- a/qpdf/test_many_nulls.cc +++ b/qpdf/test_many_nulls.cc @@ -10,7 +10,7 @@ main(int argc, char* argv[]) { auto whoami = QUtil::getWhoami(argv[0]); if (argc != 2) { - std::cerr << "Usage: " << whoami << " outfile.pdf" << std::endl; + std::cerr << "Usage: " << whoami << " outfile.pdf" << '\n'; exit(2); } char const* outfile = argv[1]; diff --git a/qpdf/test_parsedoffset.cc b/qpdf/test_parsedoffset.cc index 0978bfc..8f1924e 100644 --- a/qpdf/test_parsedoffset.cc +++ b/qpdf/test_parsedoffset.cc @@ -13,7 +13,7 @@ void usage() { - std::cerr << "Usage: test_parsedoffset INPUT.pdf" << std::endl; + std::cerr << "Usage: test_parsedoffset INPUT.pdf" << '\n'; } std::string @@ -77,9 +77,9 @@ process(std::string fn, std::vector xrefs = qpdf.getXRefTable(); for (auto const& oh: qpdf.getAllObjects()) { - if (xrefs.count(oh.getObjGen()) == 0) { + if (!xrefs.contains(oh.getObjGen())) { std::cerr << oh.getObjectID() << "/" << oh.getGeneration() - << " is not found in xref table" << std::endl; + << " is not found in xref table" << '\n'; std::exit(2); } @@ -89,7 +89,7 @@ process(std::string fn, std::vector(xref.getObjStreamNumber()); break; default: - std::cerr << "unknown xref entry type" << std::endl; + std::cerr << "unknown xref entry type" << '\n'; std::exit(2); } @@ -120,25 +120,25 @@ main(int argc, char* argv[]) process(argv[1], table); for (size_t i = 0; i < table.size(); ++i) { - if (table[i].size() == 0) { + if (table[i].empty()) { continue; } std::sort(table[i].begin(), table[i].end()); if (i == 0) { - std::cout << "--- objects not in streams ---" << std::endl; + std::cout << "--- objects not in streams ---" << '\n'; } else { - std::cout << "--- objects in stream " << i << " ---" << std::endl; + std::cout << "--- objects in stream " << i << " ---" << '\n'; } for (auto const& iter: table[i]) { - std::cout << iter.second << std::endl; + std::cout << iter.second << '\n'; } } - std::cout << "succeeded" << std::endl; + std::cout << "succeeded" << '\n'; } catch (std::exception& e) { - std::cerr << e.what() << std::endl; + std::cerr << e.what() << '\n'; std::exit(2); } diff --git a/qpdf/test_pdf_doc_encoding.cc b/qpdf/test_pdf_doc_encoding.cc index 6a16f16..ef0bac1 100644 --- a/qpdf/test_pdf_doc_encoding.cc +++ b/qpdf/test_pdf_doc_encoding.cc @@ -9,7 +9,7 @@ static char const* whoami = nullptr; void usage() { - std::cerr << "Usage: " << whoami << " infile" << std::endl; + std::cerr << "Usage: " << whoami << " infile" << '\n'; exit(2); } @@ -28,7 +28,7 @@ main(int argc, char* argv[]) char const* infilename = argv[1]; for (auto const& line: QUtil::read_lines_from_file(infilename)) { QPDFObjectHandle str = QPDFObjectHandle::newString(line); - std::cout << str.getUTF8Value() << std::endl; + std::cout << str.getUTF8Value() << '\n'; } return 0; } diff --git a/qpdf/test_pdf_unicode.cc b/qpdf/test_pdf_unicode.cc index a459369..e213046 100644 --- a/qpdf/test_pdf_unicode.cc +++ b/qpdf/test_pdf_unicode.cc @@ -9,7 +9,7 @@ static char const* whoami = nullptr; void usage() { - std::cerr << "Usage: " << whoami << " infile" << std::endl; + std::cerr << "Usage: " << whoami << " infile" << '\n'; exit(2); } @@ -28,7 +28,7 @@ main(int argc, char* argv[]) char const* infilename = argv[1]; for (auto const& line: QUtil::read_lines_from_file(infilename)) { QPDFObjectHandle str = QPDFObjectHandle::newUnicodeString(line); - std::cout << str.getUTF8Value() << " // " << str.unparseBinary() << std::endl; + std::cout << str.getUTF8Value() << " // " << str.unparseBinary() << '\n'; } return 0; } diff --git a/qpdf/test_renumber.cc b/qpdf/test_renumber.cc index 3eaa889..b3499a8 100644 --- a/qpdf/test_renumber.cc +++ b/qpdf/test_renumber.cc @@ -14,11 +14,11 @@ void usage() { - std::cerr << "Usage: test_renumber [OPTION] INPUT.pdf" << std::endl - << "Option:" << std::endl - << " --object-streams=preserve|disable|generate" << std::endl - << " --linearize" << std::endl - << " --preserve-unreferenced" << std::endl; + std::cerr << "Usage: test_renumber [OPTION] INPUT.pdf" << '\n' + << "Option:" << '\n' + << " --object-streams=preserve|disable|generate" << '\n' + << " --linearize" << '\n' + << " --preserve-unreferenced" << '\n'; } bool @@ -26,45 +26,45 @@ compare(QPDFObjectHandle a, QPDFObjectHandle b) { static std::set visited; if (a.isIndirect()) { - if (visited.count(a.getObjGen())) { + if (visited.contains(a.getObjGen())) { return true; } visited.insert(a.getObjGen()); } if (a.getTypeCode() != b.getTypeCode()) { - std::cerr << "different type code" << std::endl; + std::cerr << "different type code" << '\n'; return false; } switch (a.getTypeCode()) { case ::ot_boolean: if (a.getBoolValue() != b.getBoolValue()) { - std::cerr << "different boolean" << std::endl; + std::cerr << "different boolean" << '\n'; return false; } break; case ::ot_integer: if (a.getIntValue() != b.getIntValue()) { - std::cerr << "different integer" << std::endl; + std::cerr << "different integer" << '\n'; return false; } break; case ::ot_real: if (a.getRealValue() != b.getRealValue()) { - std::cerr << "different real" << std::endl; + std::cerr << "different real" << '\n'; return false; } break; case ::ot_string: if (a.getStringValue() != b.getStringValue()) { - std::cerr << "different string" << std::endl; + std::cerr << "different string" << '\n'; return false; } break; case ::ot_name: if (a.getName() != b.getName()) { - std::cerr << "different name" << std::endl; + std::cerr << "different name" << '\n'; return false; } break; @@ -74,13 +74,13 @@ compare(QPDFObjectHandle a, QPDFObjectHandle b) std::vector objs_b = b.getArrayAsVector(); size_t items = objs_a.size(); if (items != objs_b.size()) { - std::cerr << "different array size" << std::endl; + std::cerr << "different array size" << '\n'; return false; } for (size_t i = 0; i < items; ++i) { if (!compare(objs_a[i], objs_b[i])) { - std::cerr << "different array item" << std::endl; + std::cerr << "different array item" << '\n'; return false; } } @@ -91,13 +91,13 @@ compare(QPDFObjectHandle a, QPDFObjectHandle b) std::set keys_a = a.getKeys(); std::set keys_b = b.getKeys(); if (keys_a != keys_b) { - std::cerr << "different dictionary keys" << std::endl; + std::cerr << "different dictionary keys" << '\n'; return false; } for (auto const& key: keys_a) { if (!compare(a.getKey(key), b.getKey(key))) { - std::cerr << "different dictionary item" << std::endl; + std::cerr << "different dictionary item" << '\n'; return false; } } @@ -106,10 +106,10 @@ compare(QPDFObjectHandle a, QPDFObjectHandle b) case ::ot_null: break; case ::ot_stream: - std::cout << "stream objects are not compared" << std::endl; + std::cout << "stream objects are not compared" << '\n'; break; default: - std::cerr << "unknown object type" << std::endl; + std::cerr << "unknown object type" << '\n'; std::exit(2); } @@ -120,23 +120,22 @@ bool compare_xref_table(std::map a, std::map b) { if (a.size() != b.size()) { - std::cerr << "different size" << std::endl; + std::cerr << "different size" << '\n'; return false; } for (auto const& iter: a) { - std::cout << "xref entry for " << iter.first.getObj() << "/" << iter.first.getGen() - << std::endl; + std::cout << "xref entry for " << iter.first.getObj() << "/" << iter.first.getGen() << '\n'; - if (b.count(iter.first) == 0) { - std::cerr << "not found" << std::endl; + if (!b.contains(iter.first)) { + std::cerr << "not found" << '\n'; return false; } QPDFXRefEntry xref_a = iter.second; QPDFXRefEntry xref_b = b[iter.first]; if (xref_a.getType() != xref_b.getType()) { - std::cerr << "different xref entry type" << std::endl; + std::cerr << "different xref entry type" << '\n'; return false; } @@ -145,19 +144,19 @@ compare_xref_table(std::map a, std::map(buf->getBuffer()), buf->getSize()); std::map xrefs_ren = qpdf_ren.getXRefTable(); - std::cout << "--- compare between input and renumbered objects ---" << std::endl; + std::cout << "--- compare between input and renumbered objects ---" << '\n'; for (auto const& iter: objs_in) { QPDFObjGen og_in = iter.getObjGen(); QPDFObjGen og_ren = w.getRenumberedObjGen(og_in); std::cout << "input " << og_in.getObj() << "/" << og_in.getGen() << " -> renumbered " - << og_ren.getObj() << "/" << og_ren.getGen() << std::endl; + << og_ren.getObj() << "/" << og_ren.getGen() << '\n'; if (og_ren.getObj() == 0) { - std::cout << "deleted" << std::endl; + std::cout << "deleted" << '\n'; continue; } if (!compare(iter, qpdf_ren.getObjectByObjGen(og_ren))) { - std::cerr << "different" << std::endl; + std::cerr << "different" << '\n'; std::exit(2); } } - std::cout << "complete" << std::endl; + std::cout << "complete" << '\n'; - std::cout << "--- compare between written and reloaded xref tables ---" << std::endl; + std::cout << "--- compare between written and reloaded xref tables ---" << '\n'; if (!compare_xref_table(xrefs_w, xrefs_ren)) { - std::cerr << "different" << std::endl; + std::cerr << "different" << '\n'; std::exit(2); } - std::cout << "complete" << std::endl; + std::cout << "complete" << '\n'; - std::cout << "succeeded" << std::endl; + std::cout << "succeeded" << '\n'; } catch (std::exception& e) { - std::cerr << e.what() << std::endl; + std::cerr << e.what() << '\n'; std::exit(2); } diff --git a/qpdf/test_shell_glob.cc b/qpdf/test_shell_glob.cc index b916e3d..6df9782 100644 --- a/qpdf/test_shell_glob.cc +++ b/qpdf/test_shell_glob.cc @@ -32,11 +32,11 @@ realmain(int argc, char* argv[]) bool passed = (found_star && (argc == 2)); #endif if (passed) { - std::cout << "PASSED" << std::endl; + std::cout << "PASSED" << '\n'; } else { - std::cout << "FAILED" << std::endl; + std::cout << "FAILED" << '\n'; for (int i = 1; i < argc; ++i) { - std::cout << argv[i] << std::endl; + std::cout << argv[i] << '\n'; } } return 0; diff --git a/qpdf/test_tokenizer.cc b/qpdf/test_tokenizer.cc index 28aa306..773b586 100644 --- a/qpdf/test_tokenizer.cc +++ b/qpdf/test_tokenizer.cc @@ -16,7 +16,7 @@ static char const* whoami = nullptr; void usage() { - std::cerr << "Usage: " << whoami << " [-maxlen len | -no-ignorable] filename" << std::endl; + std::cerr << "Usage: " << whoami << " [-maxlen len | -no-ignorable] filename" << '\n'; exit(2); } @@ -115,10 +115,10 @@ try_skipping( char const* what, Finder& f) { - std::cout << "skipping to " << what << std::endl; + std::cout << "skipping to " << what << '\n'; qpdf_offset_t offset = is->tell(); if (!is->findFirst(what, offset, 0, f)) { - std::cout << what << " not found" << std::endl; + std::cout << what << " not found" << '\n'; is->seek(offset, SEEK_SET); } } @@ -133,7 +133,7 @@ dump_tokens( bool skip_inline_images) { Finder f1(is, "endstream"); - std::cout << "--- BEGIN " << label << " ---" << std::endl; + std::cout << "--- BEGIN " << label << " ---" << '\n'; bool done = false; QPDFTokenizer tokenizer; tokenizer.allowEOF(); @@ -145,7 +145,7 @@ dump_tokens( QPDFTokenizer::Token token = tokenizer.readToken(is, "test", true, inline_image_offset ? 0 : max_len); if (inline_image_offset && (token.getType() == QPDFTokenizer::tt_bad)) { - std::cout << "EI not found; resuming normal scanning" << std::endl; + std::cout << "EI not found; resuming normal scanning" << '\n'; is->seek(inline_image_offset, SEEK_SET); inline_image_offset = 0; continue; @@ -163,7 +163,7 @@ dump_tokens( if (!token.getErrorMessage().empty()) { std::cout << " (" << token.getErrorMessage() << ")"; } - std::cout << std::endl; + std::cout << '\n'; if (skip_streams && (token == QPDFTokenizer::Token(QPDFTokenizer::tt_word, "stream"))) { try_skipping(tokenizer, is, max_len, "endstream", f1); } else if ( @@ -176,7 +176,7 @@ dump_tokens( done = true; } } - std::cout << "--- END " << label << " ---" << std::endl; + std::cout << "--- END " << label << " ---" << '\n'; } static void diff --git a/qpdf/test_unicode_filenames.cc b/qpdf/test_unicode_filenames.cc index 35ad7c7..17b1d1c 100644 --- a/qpdf/test_unicode_filenames.cc +++ b/qpdf/test_unicode_filenames.cc @@ -13,7 +13,7 @@ static void do_copy(FILE* in, FILE* out) { if ((in == nullptr) || (out == nullptr)) { - std::cerr << "errors opening files" << std::endl; + std::cerr << "errors opening files" << '\n'; exit(2); } char buf[10240]; @@ -22,7 +22,7 @@ do_copy(FILE* in, FILE* out) fwrite(buf, 1, len, out); } if (len != 0) { - std::cerr << "errors reading or writing" << std::endl; + std::cerr << "errors reading or writing" << '\n'; exit(2); } fclose(in); @@ -76,7 +76,7 @@ main(int argc, char* argv[]) char const* f2 = "auto-\xc3\xb6\xcf\x80.pdf"; copy(f1); copy(f2); - std::cout << "created Unicode filenames" << std::endl; + std::cout << "created Unicode filenames" << '\n'; return 0; } diff --git a/qpdf/test_xref.cc b/qpdf/test_xref.cc index bc733de..81e7d07 100644 --- a/qpdf/test_xref.cc +++ b/qpdf/test_xref.cc @@ -8,7 +8,7 @@ int main(int argc, char* argv[]) { if (argc != 2) { - std::cerr << "usage: test_xref INPUT.pdf" << std::endl; + std::cerr << "usage: test_xref INPUT.pdf" << '\n'; std::exit(2); } @@ -20,23 +20,23 @@ main(int argc, char* argv[]) std::cout << iter.first.getObj() << "/" << iter.first.getGen() << ", "; switch (iter.second.getType()) { case 0: - std::cout << "free entry" << std::endl; + std::cout << "free entry" << '\n'; break; case 1: std::cout << "uncompressed, offset = " << iter.second.getOffset() << " (0x" - << std::hex << iter.second.getOffset() << std::dec << ")" << std::endl; + << std::hex << iter.second.getOffset() << std::dec << ")" << '\n'; break; case 2: std::cout << "compressed, stream number = " << iter.second.getObjStreamNumber() - << ", stream index = " << iter.second.getObjStreamIndex() << std::endl; + << ", stream index = " << iter.second.getObjStreamIndex() << '\n'; break; default: - std::cerr << "unknown" << std::endl; + std::cerr << "unknown" << '\n'; std::exit(2); } } } catch (std::exception& e) { - std::cerr << e.what() << std::endl; + std::cerr << e.what() << '\n'; std::exit(2); } diff --git a/zlib-flate/zlib-flate.cc b/zlib-flate/zlib-flate.cc index 02a748e..9822ff5 100644 --- a/zlib-flate/zlib-flate.cc +++ b/zlib-flate/zlib-flate.cc @@ -13,11 +13,10 @@ static char const* whoami = nullptr; void usage() { - std::cerr << "Usage: " << whoami << " { -uncompress | -compress[=n] }" << std::endl - << "If n is specified with -compress, it is a zlib compression level from" - << std::endl - << "1 to 9 where lower numbers are faster and less compressed and higher" << std::endl - << "numbers are slower and more compressed" << std::endl; + std::cerr << "Usage: " << whoami << " { -uncompress | -compress[=n] }" << '\n' + << "If n is specified with -compress, it is a zlib compression level from" << '\n' + << "1 to 9 where lower numbers are faster and less compressed and higher" << '\n' + << "numbers are slower and more compressed" << '\n'; exit(2); } @@ -31,7 +30,7 @@ main(int argc, char* argv[]) } if ((argc == 2) && (strcmp(argv[1], "--version") == 0)) { - std::cout << whoami << " from qpdf version " << QPDF::QPDFVersion() << std::endl; + std::cout << whoami << " from qpdf version " << QPDF::QPDFVersion() << '\n'; exit(0); } @@ -53,7 +52,7 @@ main(int argc, char* argv[]) // Undocumented option, but that doesn't mean someone doesn't use it... // This is primarily here to support the test suite. std::cout << (Pl_Flate::zopfli_supported() ? "1" : "0") - << (Pl_Flate::zopfli_enabled() ? "1" : "0") << std::endl; + << (Pl_Flate::zopfli_enabled() ? "1" : "0") << '\n'; return 0; } else { usage(); @@ -68,8 +67,7 @@ main(int argc, char* argv[]) auto flate = std::make_shared("flate", out.get(), action); flate->setWarnCallback([&warn](char const* msg, int code) { warn = true; - std::cerr << whoami << ": WARNING: zlib code " << code << ", msg = " << msg - << std::endl; + std::cerr << whoami << ": WARNING: zlib code " << code << ", msg = " << msg << '\n'; }); unsigned char buf[10000]; @@ -84,7 +82,7 @@ main(int argc, char* argv[]) } flate->finish(); } catch (std::exception& e) { - std::cerr << whoami << ": " << e.what() << std::endl; + std::cerr << whoami << ": " << e.what() << '\n'; exit(2); }