coyote/blankie/escape.cpp

43 lines
915 B
C++

#include <stdexcept>
#include "escape.h"
static inline const char* get_replacement(char c);
namespace blankie {
namespace html {
std::string escape(const std::string& in) {
std::string out;
size_t pos = 0;
size_t last_pos = 0;
out.reserve(in.size());
while ((pos = in.find_first_of("&<>\"'", pos)) != std::string::npos) {
out.append(in, last_pos, pos - last_pos);
out.append(get_replacement(in[pos]));
pos++;
last_pos = pos;
}
if (in.size() > last_pos) {
out.append(in, last_pos);
}
return out;
}
} // namespace html
} // namespace blankie
static inline const char* get_replacement(char c) {
switch (c) {
case '&': return "&amp;";
case '<': return "&lt;";
case '>': return "&gt;";
case '"': return "&quot;";
case '\'': return "&#x27;";
default: __builtin_unreachable();
}
}