diff --git a/libqpdf/QPDFJob_config.cc b/libqpdf/QPDFJob_config.cc index 5dd8e29..d318d2d 100644 --- a/libqpdf/QPDFJob_config.cc +++ b/libqpdf/QPDFJob_config.cc @@ -1,11 +1,36 @@ #include -#include - #include +#include #include #include +#include +#include + +static void +int_usage(std::string_view option, std::integral auto min, std::integral auto max) +{ + throw QPDFUsage( + "invalid "s.append(option) + ": must be a number between " + std::to_string(min) + " and " + + std::to_string(max)); +} + +static int +to_int(std::string_view option, std::string const& value, int min, int max) +{ + int result = 0; + try { + result = std::stoi(value); + if (result < min || result > max) { + int_usage(option, min, max); + } + } catch (std::exception&) { + int_usage(option, min, max); + } + return result; +} + void QPDFJob::Config::checkConfiguration() { @@ -131,14 +156,14 @@ QPDFJob::Config::compressStreams(std::string const& parameter) QPDFJob::Config* QPDFJob::Config::compressionLevel(std::string const& parameter) { - o.m->compression_level = QUtil::string_to_int(parameter.c_str()); + o.m->compression_level = to_int("compression-level", parameter, 1, 9); return this; } QPDFJob::Config* QPDFJob::Config::jpegQuality(std::string const& parameter) { - o.m->jpeg_quality = QUtil::string_to_int(parameter.c_str()); + o.m->jpeg_quality = to_int("jpeg-quality", parameter, 0, 100); return this; } diff --git a/qpdf/qtest/arg-parsing.test b/qpdf/qtest/arg-parsing.test index 128826c..4da865e 100644 --- a/qpdf/qtest/arg-parsing.test +++ b/qpdf/qtest/arg-parsing.test @@ -15,7 +15,7 @@ cleanup(); my $td = new TestDriver('arg-parsing'); -my $n_tests = 30; +my $n_tests = 32; $td->runtest("required argument", {$td->COMMAND => "qpdf --password minimal.pdf"}, @@ -175,5 +175,17 @@ foreach my $arg (@bad_enc) $td->NORMALIZE_NEWLINES); } +$td->runtest("bad compression-level", + {$td->COMMAND => "qpdf --compression-level=false minimal.pdf"}, + {$td->REGEXP => "invalid compression-level: must be a number between 1 and 9", + $td->EXIT_STATUS => 2}, + $td->NORMALIZE_NEWLINES); + +$td->runtest("bad jpeg-quality", + {$td->COMMAND => "qpdf --jpeg-quality=101 minimal.pdf"}, + {$td->REGEXP => "invalid jpeg-quality: must be a number between 0 and 100", + $td->EXIT_STATUS => 2}, + $td->NORMALIZE_NEWLINES); + cleanup(); $td->report($n_tests);