From 6bb61f7e89e1b81e6fb1d93fa67a12d4541c664f Mon Sep 17 00:00:00 2001 From: Ahmad Samir Date: Mon, 24 Apr 2023 21:16:33 +0200 Subject: [PATCH] QValidator: de-duplicate some code QDoubleValidator didn't return Intermediate if the buffer only had one character, - or +, but it makes sense to check that there too. In a later commit that check will be moved to QLocaleData::validateChars (which will return "Intermediate" if the last character in the result buffer is -/+, in this case it's the last and only character in the buffer). Change-Id: I2f9f5b92880b7e9cc1a3ab36b5ec322f57291ee9 Reviewed-by: Edward Welbourne --- src/gui/util/qvalidator.cpp | 46 +++++++++++++++++++------------------ 1 file changed, 24 insertions(+), 22 deletions(-) diff --git a/src/gui/util/qvalidator.cpp b/src/gui/util/qvalidator.cpp index 8b0f9ac321..ce6c7a98a3 100644 --- a/src/gui/util/qvalidator.cpp +++ b/src/gui/util/qvalidator.cpp @@ -362,6 +362,23 @@ static qlonglong pow10(int exp) return result; } +template static inline +std::optional initialResultCheck(T min, T max, const QByteArray &buff) +{ + if (buff.isEmpty()) + return QValidator::Intermediate; + + char ch = buff[0]; + const bool signConflicts = (min >= 0 && ch == '-') || (max < 0 && ch == '+'); + if (signConflicts) + return QValidator::Invalid; + + if (buff.size() == 1 && (ch == '-' || ch == '+')) + return QValidator::Intermediate; + + return std::nullopt; +} + QValidator::State QIntValidator::validate(QString & input, int&) const { QByteArray buff; @@ -370,19 +387,9 @@ QValidator::State QIntValidator::validate(QString & input, int&) const return Invalid; } - if (buff.isEmpty()) - return Intermediate; - - const bool startsWithMinus(buff[0] == '-'); - if (b >= 0 && startsWithMinus) - return Invalid; - - const bool startsWithPlus(buff[0] == '+'); - if (t < 0 && startsWithPlus) - return Invalid; - - if (buff.size() == 1 && (startsWithPlus || startsWithMinus)) - return Intermediate; + std::optional opt = initialResultCheck(b, t, buff); + if (opt) + return *opt; bool ok; qlonglong entered = QLocaleData::bytearrayToLongLong(buff, 10, &ok); @@ -401,7 +408,7 @@ QValidator::State QIntValidator::validate(QString & input, int&) const // of a number of digits equal to or less than the max value as intermediate. int buffLength = buff.size(); - if (startsWithPlus) + if (buff[0] == '+') buffLength--; const int tLength = t != 0 ? static_cast(std::log10(qAbs(t))) + 1 : 1; @@ -651,14 +658,9 @@ QValidator::State QDoubleValidatorPrivate::validateWithLocale(QString &input, QL return QValidator::Invalid; } - if (buff.isEmpty()) - return QValidator::Intermediate; - - if (q->b >= 0 && buff.startsWith('-')) - return QValidator::Invalid; - - if (q->t < 0 && buff.startsWith('+')) - return QValidator::Invalid; + std::optional opt = initialResultCheck(q->b, q->t, buff); + if (opt) + return *opt; bool ok = false; double i = locale.toDouble(input, &ok); // returns 0.0 if !ok