bux API Reference 1.9.0
Static library of whatever are seen required in general purpose but not directly supported from Modern C++. Or whatever reusable originated from my side projects.
Loading...
Searching...
No Matches
EZScape.cpp
Go to the documentation of this file.
1#include "EZScape.h"
2#include "XException.h" // THROW_AS()
3#include <cctype> // std::isalnum()
4#include <charconv> // std::from_chars()
5#include <cstring> // std::strchr()
6#include <format> // std::format()
7
8namespace bux {
9
10//
11// Externals
12//
13std::string easy_escape(std::string_view src)
16{
17 std::string ret;
18 for (char c: src)
19 {
20 if (c && (std::isalnum(c) || std::strchr("-_.~", c)))
21 ret += c;
22 else
23 ret += std::format("%{:02X}", (int)(unsigned char)c);
24 }
25 return ret;
26}
27
28std::string easy_unescape(std::string_view src)
31{
32 std::string ret;
33 for (size_t i = 0, n = src.size(); i < n;)
34 {
35 const char ch = src[i++];
36 if (ch == '%')
37 {
38 // Convert the two hexadecimal digits after '%'
39 unsigned t;
40 const auto p = src.data() + i;
41 if (i + 2 <= n && std::errc{} == std::from_chars(p, p+2, t, 16).ec)
42 ret += char(t);
43 else
44 THROW_AS(std::invalid_argument, "Invalid percent-encoded string.");
45
46 i += 2;
47 }
48 else
49 ret += ch;
50 }
51 return ret;
52}
53
54} //namespace bux
#define THROW_AS(exp_class, fmtStr,...)
Definition XException.h:22
THE common namespace of bux library.
Definition AtomiX.cpp:3
std::string easy_escape(std::string_view src)
Definition EZScape.cpp:13
std::string easy_unescape(std::string_view src)
Definition EZScape.cpp:28