string-helper.cpp
Go to the documentation of this file.
1 /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
2 /*
3  * Copyright (c) 2013-2023 Regents of the University of California.
4  *
5  * This file is part of ndn-cxx library (NDN C++ library with eXperimental eXtensions).
6  *
7  * ndn-cxx library is free software: you can redistribute it and/or modify it under the
8  * terms of the GNU Lesser General Public License as published by the Free Software
9  * Foundation, either version 3 of the License, or (at your option) any later version.
10  *
11  * ndn-cxx library is distributed in the hope that it will be useful, but WITHOUT ANY
12  * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
13  * PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
14  *
15  * You should have received copies of the GNU General Public License and GNU Lesser
16  * General Public License along with ndn-cxx, e.g., in COPYING.md file. If not, see
17  * <http://www.gnu.org/licenses/>.
18  *
19  * See AUTHORS.md for complete list of ndn-cxx authors and contributors.
20  */
21 
23 
29 #include "ndn-cxx/util/scope.hpp"
30 
31 #include <sstream>
32 
33 namespace ndn {
34 
35 void
36 printHex(std::ostream& os, uint64_t num, bool wantUpperCase)
37 {
38  auto oldFlags = os.flags();
39  auto restoreFlags = make_scope_exit([&] {
40  os.flags(oldFlags);
41  });
42 
43  // std::showbase doesn't work with number 0
44  os << "0x" << std::noshowbase << std::noshowpos
45  << (wantUpperCase ? std::uppercase : std::nouppercase)
46  << std::hex << num;
47 }
48 
49 void
50 printHex(std::ostream& os, span<const uint8_t> buffer, bool wantUpperCase)
51 {
52  namespace tr = security::transform;
53  tr::bufferSource(buffer) >> tr::hexEncode(wantUpperCase) >> tr::streamSink(os);
54 }
55 
56 std::string
57 toHex(span<const uint8_t> buffer, bool wantUpperCase)
58 {
59  std::ostringstream result;
60  printHex(result, buffer, wantUpperCase);
61  return result.str();
62 }
63 
64 shared_ptr<Buffer>
65 fromHex(std::string_view hexString)
66 {
67  namespace tr = security::transform;
68 
69  OBufferStream os;
70  try {
71  tr::bufferSource(hexString) >> tr::hexDecode() >> tr::streamSink(os);
72  }
73  catch (const tr::Error& e) {
74  NDN_THROW_NESTED(StringHelperError("Conversion from hex failed: "s + e.what()));
75  }
76 
77  return os.buf();
78 }
79 
80 std::string
81 escape(std::string_view str)
82 {
83  std::ostringstream os;
84  escape(os, str);
85  return os.str();
86 }
87 
88 void
89 escape(std::ostream& os, std::string_view str)
90 {
91  for (auto c : str) {
92  // Unreserved characters don't need to be escaped.
93  if ((c >= 'a' && c <= 'z') ||
94  (c >= 'A' && c <= 'Z') ||
95  (c >= '0' && c <= '9') ||
96  c == '-' || c == '.' ||
97  c == '_' || c == '~') {
98  os << c;
99  }
100  else {
101  os << '%';
102  os << toHexChar((c & 0xf0) >> 4);
103  os << toHexChar(c & 0xf);
104  }
105  }
106 }
107 
108 std::string
109 unescape(std::string_view str)
110 {
111  std::ostringstream os;
112  unescape(os, str);
113  return os.str();
114 }
115 
116 void
117 unescape(std::ostream& os, std::string_view str)
118 {
119  for (size_t i = 0; i < str.size(); ++i) {
120  if (str[i] == '%' && i + 2 < str.size()) {
121  int hi = fromHexChar(str[i + 1]);
122  int lo = fromHexChar(str[i + 2]);
123 
124  if (hi < 0 || lo < 0)
125  // Invalid hex characters, so just keep the escaped string.
126  os << str[i] << str[i + 1] << str[i + 2];
127  else
128  os << static_cast<char>((hi << 4) | lo);
129 
130  // Skip ahead past the escaped value.
131  i += 2;
132  }
133  else {
134  // Just copy through.
135  os << str[i];
136  }
137  }
138 }
139 
140 } // namespace ndn
An output stream that writes to a Buffer.
std::shared_ptr< Buffer > buf()
Return a shared pointer to the underlying buffer.
#define NDN_THROW_NESTED(e)
Definition: exception.hpp:65
unique_ptr< Sink > streamSink(std::ostream &os)
Definition: stream-sink.cpp:51
unique_ptr< Transform > hexDecode()
Definition: hex-decode.cpp:106
unique_ptr< Transform > hexEncode(bool useUpperCase)
Definition: hex-encode.cpp:62
Definition: data.cpp:25
void printHex(std::ostream &os, uint64_t num, bool wantUpperCase)
Output the hex representation of num to the output stream os.
std::string escape(std::string_view str)
Percent-encode a string.
std::string toHex(span< const uint8_t > buffer, bool wantUpperCase)
Return a string containing the hex representation of the bytes in buffer.
shared_ptr< Buffer > fromHex(std::string_view hexString)
Convert a hex string to a raw byte buffer.
constexpr int fromHexChar(char c) noexcept
Convert the hex character c to an integer in [0, 15], or -1 if it's not a hex character.
std::string unescape(std::string_view str)
Decode a percent-encoded string.
constexpr char toHexChar(unsigned int n, bool wantUpperCase=true) noexcept
Convert (the least significant nibble of) n to the corresponding hex character.