Vcsn  2.2a
Be Rational
escape.cc
Go to the documentation of this file.
1 #include <vcsn/misc/escape.hh>
2 
3 #include <cctype>
4 #include <cstring> // strchr
5 #include <iomanip>
6 #include <iostream>
7 #include <sstream>
8 
9 namespace vcsn
10 {
11  // Accept int to catch EOF too.
12  std::ostream&
13  str_escape(std::ostream& os, const int c, const char* special)
14  {
15  std::ios_base::fmtflags flags = os.flags(std::ios_base::hex);
16  char fill = os.fill('0');
17  switch (c)
18  {
19  case -1: os << "<end-of-file>"; break;
20  case '\\': os << "\\\\"; break;
21  case '\n': os << "\\n"; break;
22  default:
23  if (0 <= c && c <= 0177 && std::isprint(c))
24  {
25  if (special && strchr(special, c))
26  os << '\\';
27  os << uint8_t(c);
28  }
29  else
30  // Turn into an unsigned, otherwise if c has its highest bit
31  // set, it will be interpreted as a negative char, which
32  // will be mapped to a negative int. So for instance c =
33  // 255 is mapped to \xFFFFFFF instead of \xFF.
34  //
35  // This happens only when char is "signed char". Which is
36  // common.
37  os << "\\x" << std::setw(2) << int(uint8_t(c));
38  break;
39  }
40  os.fill(fill);
41  os.flags(flags);
42  return os;
43  }
44 
45  std::string
46  str_escape(const int c, const char* special)
47  {
48  std::ostringstream o;
49  str_escape(o, c, special);
50  return o.str();
51  }
52 
53  std::ostream&
54  str_escape(std::ostream& o, const std::string& str, const char* special)
55  {
56  for (auto c: str)
57  str_escape(o, c, special);
58  return o;
59  }
60 
61  std::string
62  str_escape(const std::string& s, const char* special)
63  {
64  std::ostringstream o;
65  str_escape(o, s, special);
66  return o.str();
67  }
68 }
std::ostringstream os
The output stream: the corresponding C++ snippet to compile.
Definition: translate.cc:382
std::ostream & str_escape(std::ostream &os, const std::string &str, const char *special=nullptr)
Output a string, escaping special characters.
Definition: escape.cc:54
Definition: a-star.hh:8