InspIRCd  3.0
convto.h
1 /*
2  * InspIRCd -- Internet Relay Chat Daemon
3  *
4  * Copyright (C) 2020 Matt Schatz <[email protected]>
5  * Copyright (C) 2017-2019 Sadie Powell <[email protected]>
6  * Copyright (C) 2016 Attila Molnar <[email protected]>
7  *
8  * This file is part of InspIRCd. InspIRCd is free software: you can
9  * redistribute it and/or modify it under the terms of the GNU General Public
10  * License as published by the Free Software Foundation, version 2.
11  *
12  * This program is distributed in the hope that it will be useful, but WITHOUT
13  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
14  * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
15  * details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with this program. If not, see <http://www.gnu.org/licenses/>.
19  */
20 
21 
22 #pragma once
23 
26 template<typename T> inline std::string ConvNumeric(const T& in)
27 {
28  if (in == 0)
29  return "0";
30  T quotient = in;
31  std::string out;
32  while (quotient)
33  {
34  out += "0123456789"[std::abs((long)quotient % 10)];
35  quotient /= 10;
36  }
37  if (in < 0)
38  out += '-';
39  std::reverse(out.begin(), out.end());
40  return out;
41 }
42 
45 inline std::string ConvToStr(const int in)
46 {
47  return ConvNumeric(in);
48 }
49 
52 inline std::string ConvToStr(const long in)
53 {
54  return ConvNumeric(in);
55 }
56 
59 inline std::string ConvToStr(const char* in)
60 {
61  return in;
62 }
63 
66 inline std::string ConvToStr(const bool in)
67 {
68  return (in ? "1" : "0");
69 }
70 
73 inline std::string ConvToStr(char in)
74 {
75  return std::string(1, in);
76 }
77 
78 inline const std::string& ConvToStr(const std::string& in)
79 {
80  return in;
81 }
82 
85 template <class T> inline std::string ConvToStr(const T& in)
86 {
87  std::stringstream tmp;
88  if (!(tmp << in))
89  return std::string();
90  return tmp.str();
91 }
92 
95 template<typename TOut> inline TOut ConvToNum(const std::string& in)
96 {
97  TOut ret;
98  std::istringstream tmp(in);
99  if (!(tmp >> ret))
100  return 0;
101  return ret;
102 }
103 
104 template<> inline char ConvToNum<char>(const std::string& in)
105 {
106  // We specialise ConvToNum for char to avoid istringstream treating
107  // the input as a character literal.
108  int16_t num = ConvToNum<int16_t>(in);
109  return num >= INT8_MIN && num <= INT8_MAX ? num : 0;
110 }
111 
112 template<> inline unsigned char ConvToNum<unsigned char>(const std::string& in)
113 {
114  // We specialise ConvToNum for unsigned char to avoid istringstream
115  // treating the input as a character literal.
116  uint16_t num = ConvToNum<uint16_t>(in);
117  return num <= UINT8_MAX ? num : 0;
118 }