-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCChar.h
79 lines (65 loc) · 2.47 KB
/
CChar.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
#ifndef COOL_CCHAR_H_
#define COOL_CCHAR_H_
#include <array>
#include <cctype>
#include <ostream>
///////////////////////////////////////////////////////////////////////////////
// CChar
//
// Convert a char to a printable string, escaping it if necessary.
//
///////////////////////////////////////////////////////////////////////////////
namespace cool
{
class CChar
{
public:
using value_type = char;
using string_type = std::array<char, 5>;
using const_pointer = value_type const*;
private:
static constexpr string_type SimpleEscapeSequence(char c) noexcept
{ return string_type{'\\', c, '\0'}; }
static constexpr string_type Char(char c) noexcept
{ return string_type{c, '\0'}; }
static constexpr string_type OctalEscapeSequence(unsigned char uc) noexcept
{ return string_type{'\\',
"01234567"[uc / 64],
"01234567"[uc % 64 / 8],
"01234567"[uc % 8],
'\0'}; }
static constexpr string_type EscapeSequence(char c) noexcept
{
switch (c)
{
case '\'':
case '\"':
case '\?':
case '\\': return SimpleEscapeSequence(c);
case '\a': return SimpleEscapeSequence('a');
case '\b': return SimpleEscapeSequence('b');
case '\f': return SimpleEscapeSequence('f');
case '\n': return SimpleEscapeSequence('n');
case '\r': return SimpleEscapeSequence('r');
case '\t': return SimpleEscapeSequence('t');
case '\v': return SimpleEscapeSequence('v');
default : return isprint(c) ? Char(c) : OctalEscapeSequence(c);
};
}
public:
explicit constexpr CChar(value_type c) noexcept
: m_cchar{EscapeSequence(c)}
, m_c{c}
{}
constexpr value_type get() const noexcept { return m_c; }
constexpr string_type str() const noexcept { return m_cchar; }
constexpr const_pointer data() const noexcept { return m_cchar.data(); }
constexpr const_pointer c_str() const noexcept { return m_cchar.data(); }
friend std::ostream& operator<<(std::ostream& os, CChar const& that)
{ return os << that.c_str(); }
private:
string_type m_cchar;
value_type m_c;
};
} // cool namespace
#endif /* COOL_CCHAR_H_ */