Perform LowerCase & UpperCase transformations in-place

- Refactored to share implementation and reduce code duplication.
This commit is contained in:
Eduardo Arias 2024-08-19 08:06:00 -07:00
parent fd8a979463
commit 4670710376
3 changed files with 26 additions and 24 deletions

View File

@ -16,7 +16,7 @@
#include "lower_case.h" #include "lower_case.h"
#include <locale> #include <cctype>
namespace modsecurity::actions::transformations { namespace modsecurity::actions::transformations {
@ -26,17 +26,9 @@ LowerCase::LowerCase(const std::string &a)
: Transformation(a) { : Transformation(a) {
} }
bool LowerCase::transform(std::string &val, const Transaction *trans) const { bool LowerCase::transform(std::string &value, const Transaction *trans) const {
std::locale loc; return convert(value, [](auto c) {
std::string value(val); return std::tolower(c); });
for (std::string::size_type i=0; i < value.length(); ++i) {
value[i] = std::tolower(value[i], loc);
}
const auto changed = val != value;
val = value;
return changed;
} }

View File

@ -18,6 +18,8 @@
#include "transformation.h" #include "transformation.h"
#include <algorithm>
namespace modsecurity::actions::transformations { namespace modsecurity::actions::transformations {
class LowerCase : public Transformation { class LowerCase : public Transformation {
@ -25,6 +27,19 @@ class LowerCase : public Transformation {
explicit LowerCase(const std::string &action); explicit LowerCase(const std::string &action);
bool transform(std::string &value, const Transaction *trans) const override; bool transform(std::string &value, const Transaction *trans) const override;
template<typename Operation>
static bool convert(std::string &val, Operation op) {
bool changed = false;
std::transform(val.begin(), val.end(), val.data(),
[&](auto c) {
const auto nc = op(c);
if(nc != c) changed = true;
return nc; });
return changed;
}
}; };
} // namespace modsecurity::actions::transformations } // namespace modsecurity::actions::transformations

View File

@ -16,7 +16,10 @@
#include "upper_case.h" #include "upper_case.h"
#include <locale> #include <cctype>
#include "lower_case.h"
namespace modsecurity::actions::transformations { namespace modsecurity::actions::transformations {
@ -25,17 +28,9 @@ UpperCase::UpperCase(const std::string &a)
: Transformation(a) { : Transformation(a) {
} }
bool UpperCase::transform(std::string &val, const Transaction *trans) const { bool UpperCase::transform(std::string &value, const Transaction *trans) const {
std::string value(val); return LowerCase::convert(value, [](auto c)
std::locale loc; { return std::toupper(c); });
for (std::string::size_type i=0; i < value.length(); ++i) {
value[i] = std::toupper(value[i], loc);
}
const auto changed = val != value;
val = value;
return changed;
} }