openMSX
escape_newline.hh
Go to the documentation of this file.
1#ifndef ESCAPE_NEWLINE_HH
2#define ESCAPE_NEWLINE_HH
3
4#include "one_of.hh"
5
6#include <string>
7#include <string_view>
8
9namespace escape_newline {
10
11[[nodiscard]] inline std::string encode(std::string_view input)
12{
13 // TODO use c++23 std::string::resize_and_overwrite()
14 std::string result;
15 result.reserve(input.size());
16 for (char c : input) {
17 if (c == one_of('\n', '\\')) {
18 if (c == '\n') c = 'n';
19 result += '\\';
20 }
21 result += c;
22 }
23 return result;
24}
25
26[[nodiscard]] inline std::string decode(std::string_view input)
27{
28 // TODO use c++23 std::string::resize_and_overwrite()
29 std::string result;
30 result.reserve(input.size());
31 for (size_t i = 0, end = input.size(); i < end; ++i) {
32 char c = input[i];
33 if (c == '\\') {
34 if (++i == end) break; // error
35 c = input[i];
36 if (c == 'n') c = '\n';
37 }
38 result += c;
39 }
40 return result;
41}
42
43} // namespace escape_newline
44
45#endif
std::string decode(std::string_view input)
std::string encode(std::string_view input)
constexpr auto end(const zstring_view &x)