5 #include "lexicalcast.h"
13 /* Helper to avoid warnings about an unsigned type never being < 0 */
14 template<typename T, bool f = is_signed<T>::value>
16 { static bool eval(T v) { return v<0; } };
19 struct IsNegative<T, false>
20 { static bool eval(T) { return false; } };
22 template<typename T, bool f = is_signed<T>::value>
24 { static T eval(T v) { return -v; } };
27 struct Negate<T, false>
28 { static T eval(T v) { return (~v)+1; } };
30 /* Helper to avoid errors about ambiguous function calls since there are no
31 overloads of abs for unsigned types */
32 template<typename T, bool f = is_signed<T>::value>
34 { static T eval(T v) { return v<0 ? -v : v; } };
37 struct Absolute<T, false>
38 { static T eval(T v) { return v; } };
41 /*** Integer conversions ***/
43 const char udigits[] = "0123456789ABCDEF";
44 const char ldigits[] = "0123456789abcdef";
47 char *int_to_str(T v, const Fmt &f, char *end)
49 if(f.get_type()==Fmt::CHAR)
57 // Find out the base to use
58 unsigned base = f.get_base();
62 // Format the number, starting from the least significant digit
63 const char *digits = (f.get_uppercase() ? udigits : ldigits);
66 typename std::make_unsigned<T>::type w = Absolute<T>::eval(v);
69 *--ptr = digits[w%base];
76 char sign = (IsNegative<T>::eval(v) ? '-' : f.get_showpos() ? '+' : 0);
79 /* Zero-fill, taking base/sign size into account. The expression is a
80 bit ugly, but saves having to write code for creating the prefix both
82 unsigned pfxsize = ((f.get_showbase() && base!=10) ? base==8 ? 1 : 2 : 0) + (sign!=0);
83 for(unsigned i=(end-ptr)+pfxsize; i<f.get_width(); ++i)
87 if(f.get_showbase() && v!=0)
91 *--ptr = (f.get_uppercase() ? 'B' : 'b');
93 *--ptr = (f.get_uppercase() ? 'X' : 'x');
105 string int_to_str(T v, const Fmt &f)
107 unsigned size = max(f.get_width(), max<unsigned>(f.get_precision(), sizeof(T)*8+3));
108 char *buf = new char[size];
109 string result(int_to_str(v, f, buf+size), buf+size);
115 T str_to_int(const string &s, const Fmt &f)
118 throw lexical_error("conversion of '' to integer");
122 // See if the input starts with a sign
126 if(is_unsigned<T>::value)
127 throw lexical_error(format("conversion of '%s' to unsigned integer", s));
134 // Must have some digits to convert
136 throw lexical_error(format("conversion of '%s' to integer", s));
138 T base = f.get_base();
139 if(!base && i!=s.end())
141 // Automatic base detection requested, figure it out
142 if(*i=='0' && ++i!=s.end())
144 if(*i=='x' || *i=='X')
149 else if(*i=='b' || *i=='B')
163 for(; i!=s.end(); ++i)
166 if(*i>='0' && *i<='9')
168 else if(*i>='A' && *i<='F')
170 else if(*i>='a' && *i<='f')
173 throw lexical_error(format("conversion of '%s' to integer (base-%d)", s, base));
174 T next = result*base+digit;
175 if(next/base!=result)
176 throw lexical_error(format("conversion of '%s' to %d-bit integer", s, sizeof(T)*8));
181 result = Negate<T>::eval(result);
187 /*** Boolean conversions ***/
189 string bool_to_str(bool b, const Fmt &f)
191 if(f.get_type()==Fmt::STR)
192 return b ? "true" : "false";
194 return b ? "1" : "0";
197 bool str_to_bool(const string &s)
200 throw lexical_error("conversion of '' to boolean");
202 if(s=="1" || s=="true" || s=="yes" || s=="on")
204 else if(s=="0" || s=="false" || s=="no" || s=="off")
207 throw lexical_error(format("conversion of '%s' to boolean", s));
211 /*** Floating-point conversions ***/
214 string flt_to_str(T v, const Fmt &f)
216 if(f.get_type()==Fmt::CHAR)
217 throw format_mismatch("floating-point conversion with character format");
219 Fmt::FloatMode mode = f.get_floatmode();
220 long double w = abs(v);
221 char sign = (v<0 ? '-' : f.get_showpos() ? '+' : 0);
223 // Handle infinity and not-a-number as special cases
230 result += (f.get_uppercase() ? "NAN" : "nan");
232 result += (f.get_uppercase() ? "INF" : "inf");
233 if(result.size()<f.get_width())
234 result = string(f.get_width()-result.size(), ' ')+result;
238 /* Find out the base-10 exponent. Building up the multiplier / divisor
239 first helps with accuracy in some cases. */
251 else if(mode!=Fmt::FIXED && w<1 && w!=0)
262 // Decide how to format the number
264 unsigned leading_zeroes = 0;
266 bool showexp = false;
270 digits = point+f.get_precision();
272 else if(mode==Fmt::SCI)
274 digits = f.get_precision()+1;
279 digits = max(f.get_precision(), 1U);
280 if(exp<-4 || exp>=static_cast<int>(digits))
288 leading_zeroes = -exp;
295 w += 5.0l/pow(10.0l, static_cast<long double>(digits));
298 // Rounding bumped us to the next exponent, deal with it
300 if(mode==Fmt::AUTOFLT && exp+1==static_cast<int>(digits))
318 digits += leading_zeroes;
320 // Create a buffer and start from the end
321 unsigned size = max(f.get_width(), digits+8);
322 char *buf = new char[size];
323 char *end = buf+size;
329 ptr = int_to_str(exp, Fmt().showpos().fill('0').width(3), ptr);
330 *--ptr = (f.get_uppercase() ? 'E' : 'e');
333 // Format mantissa left-to-right
335 ptr -= digits+(point<digits || f.get_showpoint());
337 for(unsigned i=0; i<digits; ++i)
343 int digit = static_cast<int>(w);
354 if(f.get_showpoint())
356 // Radix point requested but not displayed yet, add it
360 else if(mode==Fmt::AUTOFLT && digits>point)
362 // Remove trailing zeroes from fraction and a lone radix point
375 // Add filling and sign
376 if(f.get_fill()=='0')
378 unsigned pfxlen = (sign!=0);
379 while(end-ptr+pfxlen<f.get_width())
385 string result(ptr, end);
391 T str_to_flt(const string &s, const Fmt &)
394 throw lexical_error("conversion of '' to floating-point");
398 // See if the input starts with a sign
408 // Must have some digits to convert
410 throw lexical_error(format("conversion of '%s' to floating-point", s));
416 bool point_seen = false;
417 for(; i!=s.end(); ++i)
422 throw lexical_error(format("conversion of '%s' to floating-point", s));
425 else if(*i>='0' && *i<='9')
431 else if(*i=='e' || *i=='E')
433 // We have an exponent
436 exp += str_to_int<int>(string(i, s.end()), Fmt());
437 // str_to_int has eaten the rest of the input or thrown
441 throw lexical_error(format("conversion of '%s' to floating-point", s));
444 // Scale and negate the result as needed
463 /*** String conversions ***/
465 string str_to_str(const string &s, const Fmt &f)
467 if(f.get_type()==Fmt::NUM)
468 throw format_mismatch("string conversion with numeric format");
476 void LexicalConverter::result(const string &s)
479 if(s.size()<fmt.get_width())
481 if(fmt.get_align()==Fmt::RIGHT)
482 buf = string(fmt.get_width()-s.size(), fmt.get_fill())+s;
484 buf = s+string(fmt.get_width()-s.size(), fmt.get_fill());
490 const string &LexicalConverter::get() const
493 throw lexical_error("conversion not performed");
500 void operator<<(LexicalConverter &c, char v)
502 Fmt::Type type = c.get_fmt().get_type();
504 c.result(int_to_str(v, c.get_fmt()));
506 c.result(string(1, v));
509 void operator<<(LexicalConverter &c, signed char v)
510 { c.result(int_to_str(v, c.get_fmt())); }
512 void operator<<(LexicalConverter &c, short v)
513 { c.result(int_to_str(v, c.get_fmt())); }
515 void operator<<(LexicalConverter &c, int v)
516 { c.result(int_to_str(v, c.get_fmt())); }
518 void operator<<(LexicalConverter &c, long v)
519 { c.result(int_to_str(v, c.get_fmt())); }
521 void operator<<(LexicalConverter &c, unsigned char v)
522 { c.result(int_to_str(v, c.get_fmt())); }
524 void operator<<(LexicalConverter &c, unsigned short v)
525 { c.result(int_to_str(v, c.get_fmt())); }
527 void operator<<(LexicalConverter &c, unsigned v)
528 { c.result(int_to_str(v, c.get_fmt())); }
530 void operator<<(LexicalConverter &c, unsigned long v)
531 { c.result(int_to_str(v, c.get_fmt())); }
533 void operator<<(LexicalConverter &c, long long v)
534 { c.result(int_to_str(v, c.get_fmt())); }
536 void operator<<(LexicalConverter &c, unsigned long long v)
537 { c.result(int_to_str(v, c.get_fmt())); }
539 void operator<<(LexicalConverter &c, bool v)
540 { c.result(bool_to_str(v, c.get_fmt())); }
542 void operator<<(LexicalConverter &c, float v)
543 { c.result(flt_to_str(v, c.get_fmt())); }
545 void operator<<(LexicalConverter &c, double v)
546 { c.result(flt_to_str(v, c.get_fmt())); }
548 void operator<<(LexicalConverter &c, long double v)
549 { c.result(flt_to_str(v, c.get_fmt())); }
551 void operator<<(LexicalConverter &c, const string &s)
552 { c.result(str_to_str(s, c.get_fmt())); }
554 void operator<<(LexicalConverter &c, const char *s)
555 { c.result(str_to_str(s, c.get_fmt())); }
557 void operator<<(LexicalConverter &c, const void *p)
558 { c.result(int_to_str(reinterpret_cast<intptr_t>(p), c.get_fmt())); }
563 void operator>>(const LexicalConverter &c, char &v)
565 if(c.get_fmt().get_type()==Fmt::NUM)
566 v = str_to_int<char>(c.get(), c.get_fmt());
569 const string &s = c.get();
571 throw lexical_error("conversion of '' to character");
573 throw lexical_error(format("conversion of '%s' to character", s));
578 void operator>>(const LexicalConverter &c, signed char &v)
579 { v = str_to_int<signed char>(c.get(), c.get_fmt()); }
581 void operator>>(const LexicalConverter &c, short &v)
582 { v = str_to_int<short>(c.get(), c.get_fmt()); }
584 void operator>>(const LexicalConverter &c, int &v)
585 { v = str_to_int<int>(c.get(), c.get_fmt()); }
587 void operator>>(const LexicalConverter &c, long &v)
588 { v = str_to_int<long>(c.get(), c.get_fmt()); }
590 void operator>>(const LexicalConverter &c, unsigned char &v)
591 { v = str_to_int<unsigned char>(c.get(), c.get_fmt()); }
593 void operator>>(const LexicalConverter &c, unsigned short &v)
594 { v = str_to_int<unsigned short>(c.get(), c.get_fmt()); }
596 void operator>>(const LexicalConverter &c, unsigned int &v)
597 { v = str_to_int<unsigned int>(c.get(), c.get_fmt()); }
599 void operator>>(const LexicalConverter &c, unsigned long &v)
600 { v = str_to_int<unsigned long>(c.get(), c.get_fmt()); }
602 void operator>>(const LexicalConverter &c, long long &v)
603 { v = str_to_int<long long>(c.get(), c.get_fmt()); }
605 void operator>>(const LexicalConverter &c, unsigned long long &v)
606 { v = str_to_int<unsigned long long>(c.get(), c.get_fmt()); }
608 void operator>>(const LexicalConverter &c, bool &v)
609 { v = str_to_bool(c.get()); }
611 void operator>>(const LexicalConverter &c, float &v)
612 { v = str_to_flt<float>(c.get(), c.get_fmt()); }
614 void operator>>(const LexicalConverter &c, double &v)
615 { v = str_to_flt<double>(c.get(), c.get_fmt()); }
617 void operator>>(const LexicalConverter &c, long double &v)
618 { v = str_to_flt<long double>(c.get(), c.get_fmt()); }
620 void operator>>(const LexicalConverter &c, string &s)
621 { s = str_to_str(c.get(), c.get_fmt()); }