xtd 0.2.0
Loading...
Searching...
No Matches
__numeric_formatter.h
Go to the documentation of this file.
1
3#pragma once
5#if !defined(__XTD_CORE_INTERNAL__)
6#error "Do not include this file: Internal use only"
7#endif
9
10#include "__binary_formatter.h"
12#include "__format_exception.h"
13#include "__sprintf.h"
14#include <algorithm>
15
17template<typename char_t, typename value_t>
18inline std::basic_string<char_t> __numeric_formatter(const std::basic_string<char_t>& fmt, value_t value, const std::locale& loc) {
19 auto format = fmt;
20 if (format.empty()) format = {'G'};
21
22 std::vector<char_t> possible_formats {'b', 'B', 'c', 'C', 'd', 'D', 'e', 'E', 'f', 'F', 'g', 'G', 'n', 'N', 'o', 'O', 'p', 'P', 'x', 'X'};
23 if (format.size() > 3 || std::find(possible_formats.begin(), possible_formats.end(), format[0]) == possible_formats.end() || (format.size() >= 2 && !std::isdigit(format[1])) || (format.size() == 3 && !std::isdigit(format[2])))
24 __format_exception("Custom format not yet implemented");
25
26 int precision = 0;
27 if (format[0] == 'b' || format[0] == 'B' || format[0] == 'd' || format[0] == 'D' || format[0] == 'o' || format[0] == 'O' || format[0] == 'x' || format[0] == 'X') {
28 try {
29 for (auto c : format.substr(1))
30 if (!std::isdigit(c) && c != ' ' && c != '+' && c != '-') __format_exception("Invalid format expression");
31 if (format.size() > 1) precision = std::stoi(format.substr(1));
32 } catch (...) {
33 __format_exception("Invalid format expression");
34 }
35 if ((format[0] == 'd' || format[0] == 'D') && precision > 0 && value < 0) precision += 1;
36 if ((format[0] == 'd' || format[0] == 'D') && precision < 0 && value < 0) precision -= 1;
37 }
38
39 std::basic_string<char_t> fmt_str({'%', '0', '*', 'l', 'l'});
40 switch (format[0]) {
41 case 'b':
42 case 'B': return __binary_formatter<char_t>(value, precision);
43 case 'd':
44 case 'D':
45 case 'G': return __sprintf((fmt_str + char_t(std::is_unsigned<value_t>::value ? 'u' : 'd')).c_str(), precision, static_cast<long long>(value));
46 case 'o':
47 case 'O': return __sprintf((fmt_str + char_t('o')).c_str(), precision, static_cast<long long>(value));
48 case 'x':
49 case 'X': return __sprintf((fmt_str + format[0]).c_str(), precision, static_cast<long long>(value));
50 default: return __floating_point_formatter(format, static_cast<long double>(value), loc);
51 }
52}
Contains __binary_formatter method.
Contains __floating_point_formatter method.
Contains throw format exception method.
Contains __format method.
@ c
The C key.