InspIRCd  4.0
convto.h
1 /*
2  * InspIRCd -- Internet Relay Chat Daemon
3  *
4  * Copyright (C) 2017-2019 Sadie Powell <[email protected]>
5  * Copyright (C) 2016 Attila Molnar <[email protected]>
6  *
7  * This file is part of InspIRCd. InspIRCd is free software: you can
8  * redistribute it and/or modify it under the terms of the GNU General Public
9  * License as published by the Free Software Foundation, version 2.
10  *
11  * This program is distributed in the hope that it will be useful, but WITHOUT
12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
13  * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
14  * details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program. If not, see <http://www.gnu.org/licenses/>.
18  */
19 
20 
21 #pragma once
22 
26 inline const std::string& ConvToStr(const std::string& in)
27 {
28  return in;
29 }
30 
34 inline std::string ConvToStr(const std::string_view& in)
35 {
36  return std::string(in);
37 }
38 
42 inline std::string ConvToStr(const char* in)
43 {
44  return std::string(in);
45 }
46 
50 inline std::string ConvToStr(char in)
51 {
52  return std::string(1, in);
53 }
54 
58 inline std::string ConvToStr(unsigned char in)
59 {
60  return std::string(1, in);
61 }
62 
66 inline std::string ConvToStr(const bool in)
67 {
68  return (in ? "1" : "0");
69 }
70 
74 template<typename Stringable>
75 inline std::enable_if_t<std::is_arithmetic_v<Stringable>, std::string> ConvToStr(const Stringable& in)
76 {
77  return std::to_string(in);
78 }
79 
83 template <class T>
84 inline std::enable_if_t<!std::is_arithmetic_v<T>, std::string> ConvToStr(const T& in)
85 {
86  std::stringstream tmp;
87  if (!(tmp << in))
88  return std::string();
89  return tmp.str();
90 }
91 
96 template<typename Numeric>
97 inline Numeric ConvToNum(const std::string& in, Numeric def = 0)
98 {
99  Numeric ret;
100  std::istringstream tmp(in);
101  if (!(tmp >> ret))
102  return def;
103  return ret;
104 }
105 
110 template<>
111 inline char ConvToNum<char>(const std::string& in, char def)
112 {
113  int16_t num = ConvToNum<int16_t>(in);
114  return num >= INT8_MIN && num <= INT8_MAX ? static_cast<char>(num) : def;
115 }
116 
121 template<>
122 inline unsigned char ConvToNum<unsigned char>(const std::string& in, unsigned char def)
123 {
124  uint16_t num = ConvToNum<uint16_t>(in);
125  return num <= UINT8_MAX ? static_cast<unsigned char>(num) : def;
126 }