pica/utils/formdecode.cpp

47 lines
1.3 KiB
C++

// SPDX-FileCopyrightText: 2023 Yury Gubich <blue@macaw.me>
// SPDX-License-Identifier: GPL-3.0-or-later
#include "formdecode.h"
#include <sstream>
std::map<std::string, std::string> urlDecodeAndParse(const std::string_view& encoded) {
std::map<std::string, std::string> result;
std::istringstream iss(std::string(encoded.begin(), encoded.end()));
std::string pair;
while (std::getline(iss, pair, '&')) {
size_t equalsPos = pair.find('=');
if (equalsPos != std::string::npos)
result.emplace(
urlDecode(pair.substr(0, equalsPos)),
urlDecode(pair.substr(equalsPos + 1))
);
}
return result;
}
std::string urlDecode(const std::string_view& encoded) {
std::ostringstream decoded;
for (size_t i = 0; i < encoded.length(); ++i) {
if (encoded[i] == '%') {
if (i + 2 < encoded.length()) {
std::string hexStr(encoded.substr(i + 1, 2));
char hexValue = static_cast<char>(std::stoul(hexStr, nullptr, 16));
decoded.put(hexValue);
i += 2;
} else {
decoded.put(encoded[i]);
}
} else if (encoded[i] == '+') {
decoded.put(' ');
} else {
decoded.put(encoded[i]);
}
}
return decoded.str();
}