Skip to content

Commit

Permalink
add String.DecodeURI
Browse files Browse the repository at this point in the history
  • Loading branch information
sinkingsugar committed Jan 29, 2023
1 parent 0a0e2b5 commit f4016cf
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 0 deletions.
37 changes: 37 additions & 0 deletions src/core/shards/http.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,31 @@ inline std::string url_encode(const std::string_view &value) {
return escaped.str();
}

inline std::string url_decode(const std::string_view &value) {
std::string decoded;
decoded.reserve(value.size());

for (std::size_t i = 0; i < value.size(); ++i) {
if (value[i] == '%') {
if (i + 3 <= value.size()) {
int v = 0;
std::istringstream hex_stream(std::string(value.substr(i + 1, 2)));
hex_stream >> std::hex >> v;
decoded += static_cast<char>(v);
i += 2;
} else {
throw std::runtime_error("Invalid URL encoding");
}
} else if (value[i] == '+') {
decoded += ' ';
} else {
decoded += value[i];
}
}

return decoded;
}

namespace shards {
namespace Http {
#ifdef __EMSCRIPTEN__
Expand Down Expand Up @@ -891,6 +916,17 @@ struct EncodeURI {
}
};

struct DecodeURI {
std::string _output;
static SHTypesInfo inputTypes() { return CoreInfo::StringType; }
static SHTypesInfo outputTypes() { return CoreInfo::StringType; }
SHVar activate(SHContext *context, const SHVar &input) {
auto str = SHSTRVIEW(input);
_output = url_decode(str);
return Var(_output);
}
};

void registerShards() {
#ifdef __EMSCRIPTEN__
REGISTER_SHARD("Http.Get", Get);
Expand All @@ -906,6 +942,7 @@ void registerShards() {
REGISTER_SHARD("Http.SendFile", SendFile);
#endif
REGISTER_SHARD("String.EncodeURI", EncodeURI);
REGISTER_SHARD("String.DecodeURI", DecodeURI);
}
} // namespace Http
} // namespace shards
Expand Down
2 changes: 2 additions & 0 deletions src/tests/http.clj
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@
"Hello world, this is an escaping test ////"
(String.EncodeURI) (Log)
(Assert.Is "Hello%20world%2C%20this%20is%20an%20escaping%20test%20%2F%2F%2F%2F" true)
(String.DecodeURI) (Log)
(Assert.Is "Hello world, this is an escaping test ////" true)

; params
1 (ToString)
Expand Down

0 comments on commit f4016cf

Please sign in to comment.