Vcsn  2.3
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  os << "\\x" << std::setw(2) << c;
31  break;
32  }
33  os.fill(fill);
34  os.flags(flags);
35  return os;
36  }
37 
38  std::ostream&
39  str_escape(std::ostream& os, char c, const char* special)
40  {
41  // Turn into an unsigned, otherwise if c has its highest bit set,
42  // it will be interpreted as a negative char, which will be mapped
43  // to a negative int. So for instance c = 255 is mapped to
44  // \xFFFFFFF instead of \xFF.
45  //
46  // This happens only when char is "signed char". Which is common.
47  return str_escape(os, int(uint8_t(c)), special);
48  }
49 
50  std::ostream&
51  str_escape(std::ostream& o, const std::string& str, const char* special)
52  {
53  for (auto c: str)
54  str_escape(o, c, special);
55  return o;
56  }
57 }
std::ostream & str_escape(std::ostream &os, const std::string &str, const char *special=nullptr)
Output a string, escaping special characters.
Definition: escape.cc:51
Definition: a-star.hh:8
std::ostringstream os
The output stream: the corresponding C++ snippet to compile.
Definition: translate.cc:375