3 #include <msp/core/inttypes.h>
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 /* Helper to avoid errors about ambiguous function calls since there are no
23 overloads of abs for unsigned types */
24 template<typename T, bool f = is_signed<T>::value>
26 { static T eval(T v) { return v<0 ? -v : v; } };
29 struct Absolute<T, false>
30 { static T eval(T v) { return v; } };
33 /*** Integer conversions ***/
35 const char udigits[] = "0123456789ABCDEF";
36 const char ldigits[] = "0123456789abcdef";
39 char *int_to_str(T v, const Fmt &f, char *end)
41 if(f.get_type()==Fmt::CHAR)
49 // Find out the base to use
50 unsigned base = f.get_base();
54 // Format the number, starting from the least significant digit
55 const char *digits = (f.get_uppercase() ? udigits : ldigits);
58 typename std::make_unsigned<T>::type w = Absolute<T>::eval(v);
61 *--ptr = digits[w%base];
68 char sign = (IsNegative<T>::eval(v) ? '-' : f.get_showpos() ? '+' : 0);
71 /* Zero-fill, taking base/sign size into account. The expression is a
72 bit ugly, but saves having to write code for creating the prefix both
74 unsigned pfxsize = ((f.get_showbase() && base!=10) ? base==8 ? 1 : 2 : 0) + (sign!=0);
75 for(unsigned i=(end-ptr)+pfxsize; i<f.get_width(); ++i)
79 if(f.get_showbase() && v!=0)
83 *--ptr = (f.get_uppercase() ? 'B' : 'b');
85 *--ptr = (f.get_uppercase() ? 'X' : 'x');
97 string int_to_str(T v, const Fmt &f)
99 unsigned size = max(f.get_width(), max<unsigned>(f.get_precision(), sizeof(T)*8+3));
100 char *buf = new char[size];
101 string result(int_to_str(v, f, buf+size), buf+size);
107 T str_to_int(const string &s, const Fmt &f)
110 throw lexical_error("conversion of '' to integer");
114 // See if the input starts with a sign
118 if(is_unsigned<T>::value)
119 throw lexical_error(format("conversion of '%s' to unsigned integer", s));
126 // Must have some digits to convert
128 throw lexical_error(format("conversion of '%s' to integer", s));
130 T base = f.get_base();
131 if(!base && i!=s.end())
133 // Automatic base detection requested, figure it out
134 if(*i=='0' && ++i!=s.end())
136 if(*i=='x' || *i=='X')
141 else if(*i=='b' || *i=='B')
155 for(; i!=s.end(); ++i)
158 if(*i>='0' && *i<='9')
160 else if(*i>='A' && *i<='F')
162 else if(*i>='a' && *i<='f')
165 throw lexical_error(format("conversion of '%s' to integer (base-%d)", s, base));
166 T next = result*base+digit;
167 if(next/base!=result)
168 throw lexical_error(format("conversion of '%s' to %d-bit integer", s, sizeof(T)*8));
179 /*** Boolean conversions ***/
181 string bool_to_str(bool b, const Fmt &f)
183 if(f.get_type()==Fmt::STR)
184 return b ? "true" : "false";
186 return b ? "1" : "0";
189 bool str_to_bool(const string &s)
192 throw lexical_error("conversion of '' to boolean");
194 if(s=="1" || s=="true" || s=="yes" || s=="on")
196 else if(s=="0" || s=="false" || s=="no" || s=="off")
199 throw lexical_error(format("conversion of '%s' to boolean", s));
203 /*** Floating-point conversions ***/
206 string flt_to_str(T v, const Fmt &f)
208 if(f.get_type()==Fmt::CHAR)
209 throw format_mismatch("floating-point conversion with character format");
211 Fmt::FloatMode mode = f.get_floatmode();
212 long double w = abs(v);
213 char sign = (v<0 ? '-' : f.get_showpos() ? '+' : 0);
215 // Handle infinity and not-a-number as special cases
222 result += (f.get_uppercase() ? "NAN" : "nan");
224 result += (f.get_uppercase() ? "INF" : "inf");
225 if(result.size()<f.get_width())
226 result = string(f.get_width()-result.size(), ' ')+result;
230 /* Find out the base-10 exponent. Building up the multiplier / divisor
231 first helps with accuracy in some cases. */
243 else if(mode!=Fmt::FIXED && w<1 && w!=0)
254 // Decide how to format the number
256 unsigned leading_zeroes = 0;
258 bool showexp = false;
262 digits = point+f.get_precision();
264 else if(mode==Fmt::SCI)
266 digits = f.get_precision()+1;
271 digits = max(f.get_precision(), 1U);
272 if(exp<-4 || exp>=static_cast<int>(digits))
280 leading_zeroes = -exp;
287 w += 5.0l/pow(10.0l, static_cast<long double>(digits));
290 // Rounding bumped us to the next exponent, deal with it
292 if(mode==Fmt::AUTOFLT && exp+1==static_cast<int>(digits))
310 digits += leading_zeroes;
312 // Create a buffer and start from the end
313 unsigned size = max(f.get_width(), digits+8);
314 char *buf = new char[size];
315 char *end = buf+size;
321 ptr = int_to_str(exp, Fmt().showpos().fill('0').width(3), ptr);
322 *--ptr = (f.get_uppercase() ? 'E' : 'e');
325 // Format mantissa left-to-right
327 ptr -= digits+(point<digits || f.get_showpoint());
329 for(unsigned i=0; i<digits; ++i)
335 int digit = static_cast<int>(w);
346 if(f.get_showpoint())
348 // Radix point requested but not displayed yet, add it
352 else if(mode==Fmt::AUTOFLT && digits>point)
354 // Remove trailing zeroes from fraction and a lone radix point
367 // Add filling and sign
368 if(f.get_fill()=='0')
370 unsigned pfxlen = (sign!=0);
371 while(end-ptr+pfxlen<f.get_width())
377 string result(ptr, end);
383 T str_to_flt(const string &s, const Fmt &)
386 throw lexical_error("conversion of '' to floating-point");
390 // See if the input starts with a sign
400 // Must have some digits to convert
402 throw lexical_error(format("conversion of '%s' to floating-point", s));
408 bool point_seen = false;
409 for(; i!=s.end(); ++i)
414 throw lexical_error(format("conversion of '%s' to floating-point", s));
417 else if(*i>='0' && *i<='9')
423 else if(*i=='e' || *i=='E')
425 // We have an exponent
428 exp += str_to_int<int>(string(i, s.end()), Fmt());
429 // str_to_int has eaten the rest of the input or thrown
433 throw lexical_error(format("conversion of '%s' to floating-point", s));
436 // Scale and negate the result as needed
455 /*** String conversions ***/
457 string str_to_str(const string &s, const Fmt &f)
459 if(f.get_type()==Fmt::NUM)
460 throw format_mismatch("string conversion with numeric format");
468 void LexicalConverter::result(const string &s)
471 if(s.size()<fmt.get_width())
473 if(fmt.get_align()==Fmt::RIGHT)
474 buf = string(fmt.get_width()-s.size(), fmt.get_fill())+s;
476 buf = s+string(fmt.get_width()-s.size(), fmt.get_fill());
482 const string &LexicalConverter::get() const
485 throw lexical_error("conversion not performed");
492 void operator<<(LexicalConverter &c, char v)
494 Fmt::Type type = c.get_fmt().get_type();
496 c.result(int_to_str(v, c.get_fmt()));
498 c.result(string(1, v));
501 void operator<<(LexicalConverter &c, signed char v)
502 { c.result(int_to_str(v, c.get_fmt())); }
504 void operator<<(LexicalConverter &c, short v)
505 { c.result(int_to_str(v, c.get_fmt())); }
507 void operator<<(LexicalConverter &c, int v)
508 { c.result(int_to_str(v, c.get_fmt())); }
510 void operator<<(LexicalConverter &c, long v)
511 { c.result(int_to_str(v, c.get_fmt())); }
513 void operator<<(LexicalConverter &c, unsigned char v)
514 { c.result(int_to_str(v, c.get_fmt())); }
516 void operator<<(LexicalConverter &c, unsigned short v)
517 { c.result(int_to_str(v, c.get_fmt())); }
519 void operator<<(LexicalConverter &c, unsigned v)
520 { c.result(int_to_str(v, c.get_fmt())); }
522 void operator<<(LexicalConverter &c, unsigned long v)
523 { c.result(int_to_str(v, c.get_fmt())); }
526 void operator<<(LexicalConverter &c, long long v)
527 { c.result(int_to_str(v, c.get_fmt())); }
529 void operator<<(LexicalConverter &c, unsigned long long v)
530 { c.result(int_to_str(v, c.get_fmt())); }
533 void operator<<(LexicalConverter &c, bool v)
534 { c.result(bool_to_str(v, c.get_fmt())); }
536 void operator<<(LexicalConverter &c, float v)
537 { c.result(flt_to_str(v, c.get_fmt())); }
539 void operator<<(LexicalConverter &c, double v)
540 { c.result(flt_to_str(v, c.get_fmt())); }
542 void operator<<(LexicalConverter &c, long double v)
543 { c.result(flt_to_str(v, c.get_fmt())); }
545 void operator<<(LexicalConverter &c, const string &s)
546 { c.result(str_to_str(s, c.get_fmt())); }
548 void operator<<(LexicalConverter &c, const char *s)
549 { c.result(str_to_str(s, c.get_fmt())); }
551 void operator<<(LexicalConverter &c, const void *p)
552 { c.result(int_to_str(reinterpret_cast<IntPtr>(p), c.get_fmt())); }
557 void operator>>(const LexicalConverter &c, char &v)
559 if(c.get_fmt().get_type()==Fmt::NUM)
560 v = str_to_int<char>(c.get(), c.get_fmt());
563 const string &s = c.get();
565 throw lexical_error("conversion of '' to character");
567 throw lexical_error(format("conversion of '%s' to character", s));
572 void operator>>(const LexicalConverter &c, signed char &v)
573 { v = str_to_int<signed char>(c.get(), c.get_fmt()); }
575 void operator>>(const LexicalConverter &c, short &v)
576 { v = str_to_int<short>(c.get(), c.get_fmt()); }
578 void operator>>(const LexicalConverter &c, int &v)
579 { v = str_to_int<int>(c.get(), c.get_fmt()); }
581 void operator>>(const LexicalConverter &c, long &v)
582 { v = str_to_int<long>(c.get(), c.get_fmt()); }
584 void operator>>(const LexicalConverter &c, unsigned char &v)
585 { v = str_to_int<unsigned char>(c.get(), c.get_fmt()); }
587 void operator>>(const LexicalConverter &c, unsigned short &v)
588 { v = str_to_int<unsigned short>(c.get(), c.get_fmt()); }
590 void operator>>(const LexicalConverter &c, unsigned int &v)
591 { v = str_to_int<unsigned int>(c.get(), c.get_fmt()); }
593 void operator>>(const LexicalConverter &c, unsigned long &v)
594 { v = str_to_int<unsigned long>(c.get(), c.get_fmt()); }
597 void operator>>(const LexicalConverter &c, long long &v)
598 { v = str_to_int<long long>(c.get(), c.get_fmt()); }
600 void operator>>(const LexicalConverter &c, unsigned long long &v)
601 { v = str_to_int<unsigned long long>(c.get(), c.get_fmt()); }
604 void operator>>(const LexicalConverter &c, bool &v)
605 { v = str_to_bool(c.get()); }
607 void operator>>(const LexicalConverter &c, float &v)
608 { v = str_to_flt<float>(c.get(), c.get_fmt()); }
610 void operator>>(const LexicalConverter &c, double &v)
611 { v = str_to_flt<double>(c.get(), c.get_fmt()); }
613 void operator>>(const LexicalConverter &c, long double &v)
614 { v = str_to_flt<long double>(c.get(), c.get_fmt()); }
616 void operator>>(const LexicalConverter &c, string &s)
617 { s = str_to_str(c.get(), c.get_fmt()); }