utils: simplify/optimize escaping

This commit is contained in:
Albert S. 2020-04-19 22:45:51 +02:00
parent e435e84bfa
commit 3b2578b7f9

View File

@ -1,4 +1,4 @@
/* Copyright (c) 2018 Albert S.
/* Copyright (c) 2018-2020 Albert S.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
@ -27,28 +27,30 @@ SOFTWARE.
#include "logger.h"
#include "utils.h"
// TODO: instead of returning vector maybe provide an iterator version too.
// TODO: % may not be necessary (was in C version just to be sure against format string attacks
// TODO: hopefully not too slow looking up every character here:
const std::map<char, std::string> replacements = {{'<', "&lt;"}, {'>', "gt;"}, {'\"', "&quot;"}, {'%', "&#37;"}};
std::string utils::html_xss(std::string_view str)
{
std::string result;
int size = str.length();
for(int i = 0; i < size; i++)
for(char c : str)
{
char c = str[i];
auto val = replacements.find(c);
if(val != replacements.end())
{
result += val->second;
}
else
switch(c)
{
case '<':
result += "&lt;";
break;
case '>':
result += "&gt;";
break;
case '\"':
result += "&quot;";
break;
case '%':
result += "&#37;";
break;
default:
result += c;
}
}
return result;
}
@ -93,6 +95,7 @@ std::vector<std::string> utils::splitByString(const std::string &str, const std:
{
return splitByRegex(str, delim + "+");
}
std::vector<std::string> utils::splitByRegex(const std::string &str, const std::string &regex)
{
std::vector<std::string> result;