comparison modules/format/format.cpp @ 486:7ee8da32da98

Unify all in modules/
author David Demelier <markand@malikania.fr>
date Fri, 13 Nov 2015 09:26:46 +0100
parents
children
comparison
equal deleted inserted replaced
485:898d8b29a4f1 486:7ee8da32da98
1 /*
2 * format.cpp -- convenient function for formatting text with escape sequences
3 *
4 * Copyright (c) 2015 David Demelier <markand@malikania.fr>
5 *
6 * Permission to use, copy, modify, and/or distribute this software for any
7 * purpose with or without fee is hereby granted, provided that the above
8 * copyright notice and this permission notice appear in all copies.
9 *
10 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17 */
18
19 #include <array>
20 #include <sstream>
21 #include <unordered_map>
22
23 #include "format.h"
24
25 namespace fmt {
26
27 namespace {
28
29 const std::array<unsigned char, 17> colorsTable{
30 0, // Default
31 30, // Black
32 31, // Red
33 32, // Green
34 33, // Yellow
35 34, // Blue
36 35, // Magenta
37 36, // Cyan
38 37, // Light gray
39 90, // Dark gray
40 91, // Light red
41 92, // Light green
42 93, // Light yellow
43 94, // Light blue
44 95, // Light cyan
45 96, // White
46 97
47 };
48
49 const std::unordered_map<int, int> attributesTable{
50 { Bold, 1 },
51 { Dim, 2 },
52 { Underline, 4 },
53 { Blink, 5 },
54 { Reverse, 7 },
55 { Hidden, 8 }
56 };
57
58 } // !namespace
59
60 std::string convert(std::string input, unsigned short flags)
61 {
62 std::ostringstream oss;
63
64 #if !defined(_WIN32)
65 // Attributes
66 for (const auto &pair : attributesTable) {
67 if (flags & pair.first) {
68 oss << "\033[" << pair.second << "m";
69 }
70 }
71
72 // Background
73 if (((flags >> 11) & 0x3f) != Default) {
74 oss << "\033[" << std::to_string(colorsTable[static_cast<unsigned char>((flags >> 11) & 0x3f)] + 10) << "m";
75 }
76
77 // Foreground
78 if (((flags >> 6) & 0x3f) != Default) {
79 oss << "\033[" << std::to_string(colorsTable[static_cast<unsigned char>((flags >> 6) & 0x3f)]) << "m";
80 }
81
82 oss << std::move(input) << "\033[0m";
83 #else
84 oss << std::move(input);
85 #endif
86
87 return oss.str();
88 }
89
90 } // !fmt