mirror of
https://github.com/rad4day/Waybar.git
synced 2023-12-21 10:22:59 +01:00
utils: add sanitize_str to encode '&' etc.
gtk requires some chars (<>&"') to be encoded for them to render properly. `sanitize_str` sanitizes raw strings that have such chars and returns a properly encoded string
This commit is contained in:
24
src/util/sanitize_str.cpp
Normal file
24
src/util/sanitize_str.cpp
Normal file
@ -0,0 +1,24 @@
|
||||
#include <array>
|
||||
#include <string>
|
||||
#include <util/sanitize_str.hpp>
|
||||
#include <utility>
|
||||
|
||||
namespace waybar::util {
|
||||
// replaces ``<>&"'`` with their encoded counterparts
|
||||
std::string sanitize_string(std::string str) {
|
||||
// note: it's important that '&' is replaced first; therefor we *can't* use std::map
|
||||
const std::pair<char, std::string> replacement_table[] = {
|
||||
{'&', "&"}, {'<', "<"}, {'>', ">"}, {'"', """}, {'\'', "'"}};
|
||||
size_t startpoint;
|
||||
for (size_t i = 0; i < (sizeof(replacement_table) / sizeof(replacement_table[0])); ++i) {
|
||||
startpoint = 0;
|
||||
std::pair pair = replacement_table[i];
|
||||
while ((startpoint = str.find(pair.first, startpoint)) != std::string::npos) {
|
||||
str.replace(startpoint, 1, pair.second);
|
||||
startpoint += pair.second.length();
|
||||
}
|
||||
}
|
||||
|
||||
return str;
|
||||
}
|
||||
} // namespace waybar::util
|
Reference in New Issue
Block a user