3 #include <msp/core/inttypes.h>
5 #include "lexicalcast.h"
15 { enum { result = !(static_cast<T>(-1)>0) }; };
17 template<typename T, bool f = (sizeof(T)>sizeof(unsigned long))>
19 { typedef unsigned long Type; };
22 struct Temporary<T, true>
27 /* Helper to avoid warnings about an unsigned type never being < 0 */
28 template<typename T, bool f = IsSigned<T>::result>
30 { static bool eval(T v) { return v<0; } };
33 struct IsNegative<T, false>
34 { static bool eval(T) { return false; } };
36 /* Helper to avoid errors about ambiguous function calls since there are no
37 overloads of abs for unsigned types */
38 template<typename T, bool f = IsSigned<T>::result>
40 { static T eval(T v) { return v<0 ? -v : v; } };
43 struct Absolute<T, false>
44 { static T eval(T v) { return v; } };
47 /*** Integer conversions ***/
49 const char udigits[] = "0123456789ABCDEF";
50 const char ldigits[] = "0123456789abcdef";
53 char *int_to_str(T v, const Fmt &f, char *end)
55 if(f.get_type()==Fmt::CHAR)
63 // Find out the base to use
64 unsigned base = f.get_base();
68 // Format the number, starting from the least significant digit
69 const char *digits = (f.get_uppercase() ? udigits : ldigits);
72 typename Temporary<T>::Type w = Absolute<T>::eval(v);
75 *--ptr = digits[w%base];
82 char sign = (IsNegative<T>::eval(v) ? '-' : f.get_showpos() ? '+' : 0);
85 /* Zero-fill, taking base/sign size into account. The expression is a
86 bit ugly, but saves having to write code for creating the prefix both
88 unsigned pfxsize = ((f.get_showbase() && base!=10) ? base==8 ? 1 : 2 : 0) + (sign!=0);
89 for(unsigned i=(end-ptr)+pfxsize; i<f.get_width(); ++i)
93 if(f.get_showbase() && v!=0)
97 *--ptr = (f.get_uppercase() ? 'B' : 'b');
99 *--ptr = (f.get_uppercase() ? 'X' : 'x');
111 string int_to_str(T v, const Fmt &f)
113 unsigned size = max(f.get_width(), max<unsigned>(f.get_precision(), sizeof(T)*8+3));
114 char *buf = new char[size];
115 string result(int_to_str(v, f, buf+size), buf+size);
121 T str_to_int(const std::string &s, const Fmt &f)
124 throw lexical_error("conversion of '' to integer");
126 std::string::const_iterator i = s.begin();
128 // See if the input starts with a sign
132 if(!IsSigned<T>::result)
133 throw lexical_error(format("conversion of '%s' to unsigned integer", s));
140 // Must have some digits to convert
142 throw lexical_error(format("conversion of '%s' to integer", s));
144 T base = f.get_base();
145 if(!base && i!=s.end())
147 // Automatic base detection requested, figure it out
148 if(*i=='0' && ++i!=s.end())
150 if(*i=='x' || *i=='X')
155 else if(*i=='b' || *i=='B')
169 for(; i!=s.end(); ++i)
172 if(*i>='0' && *i<='9')
174 else if(*i>='A' && *i<='F')
176 else if(*i>='a' && *i<='f')
179 throw lexical_error(format("conversion of '%s' to integer (base-%d)", s, base));
180 T next = result*base+digit;
181 if(next/base!=result)
182 throw lexical_error(format("conversion of '%s' to %d-bit integer", s, sizeof(T)*8));
193 /*** Boolean conversions ***/
195 string bool_to_str(bool b, const Fmt &f)
197 if(f.get_type()==Fmt::STR)
198 return b ? "true" : "false";
200 return b ? "1" : "0";
203 bool str_to_bool(const string &s)
206 throw lexical_error("conversion of '' to boolean");
208 if(s=="1" || s=="true" || s=="yes" || s=="on")
210 else if(s=="0" || s=="false" || s=="no" || s=="off")
213 throw lexical_error(format("conversion of '%s' to boolean", s));
217 /*** Floating-point conversions ***/
220 string flt_to_str(T v, const Fmt &f)
222 if(f.get_type()==Fmt::CHAR)
223 throw format_mismatch("floating-point conversion with character format");
225 Fmt::FloatMode mode = f.get_floatmode();
226 long double w = abs(v);
227 char sign = (v<0 ? '-' : f.get_showpos() ? '+' : 0);
229 // Handle infinity and not-a-number as special cases
236 result += (f.get_uppercase() ? "NAN" : "nan");
238 result += (f.get_uppercase() ? "INF" : "inf");
239 if(result.size()<f.get_width())
240 result = string(f.get_width()-result.size(), ' ')+result;
244 /* Find out the base-10 exponent. Building up the multiplier / divisor
245 first helps with accuracy in some cases. */
257 else if(mode!=Fmt::FIXED && w<1 && w!=0)
268 // Decide how to format the number
271 bool showexp = false;
275 digits = point+f.get_precision();
277 else if(mode==Fmt::SCI)
279 digits = f.get_precision()+1;
284 digits = max(f.get_precision(), 1U);
285 if(exp<-4 || exp>=static_cast<int>(digits))
292 point = max(exp, 0)+1;
299 w += 5.0l/pow(10.0l, static_cast<long double>(digits));
302 // Rounding bumped us to the next exponent, deal with it
304 if(mode==Fmt::AUTOFLT && exp+1==static_cast<int>(digits))
318 // Create a buffer and start from the end
319 unsigned size = max(f.get_width(), digits+8);
320 char *buf = new char[size];
321 char *end = buf+size;
327 ptr = int_to_str(exp, Fmt().showpos().fill('0').width(3), ptr);
328 *--ptr = (f.get_uppercase() ? 'E' : 'e');
331 // Format mantissa left-to-right
333 ptr -= digits+(point<digits || f.get_showpoint());
335 for(unsigned i=0; i<digits; ++i)
339 if(showexp || static_cast<int>(i)>=-exp)
341 int digit = static_cast<int>(w);
349 if(f.get_showpoint())
351 // Radix point requested but not displayed yet, add it
355 else if(mode==Fmt::AUTOFLT && digits>point)
357 // Remove trailing zeroes from fraction and a lone radix point
370 // Add filling and sign
371 if(f.get_fill()=='0')
373 unsigned pfxlen = (sign!=0);
374 while(end-ptr+pfxlen<f.get_width())
380 string result(ptr, end);
386 T str_to_flt(const string &s, const Fmt &)
389 throw lexical_error("conversion of '' to floating-point");
391 std::string::const_iterator i = s.begin();
393 // See if the input starts with a sign
403 // Must have some digits to convert
405 throw lexical_error(format("conversion of '%s' to floating-point", s));
411 bool point_seen = false;
412 for(; i!=s.end(); ++i)
417 throw lexical_error(format("conversion of '%s' to floating-point", s));
420 else if(*i>='0' && *i<='9')
426 else if(*i=='e' || *i=='E')
428 // We have an exponent
431 exp += str_to_int<int>(string(i, s.end()), Fmt());
432 // str_to_int has eaten the rest of the input or thrown
436 throw lexical_error(format("conversion of '%s' to floating-point", s));
439 // Scale and negate the result as needed
458 /*** String conversions ***/
460 string str_to_str(const string &s, const Fmt &f)
462 if(f.get_type()==Fmt::NUM)
463 throw format_mismatch("string conversion with numeric format");
471 void LexicalConverter::result(const string &s)
473 if(s.size()<fmt.get_width())
475 if(fmt.get_align()==Fmt::RIGHT)
476 buf = string(fmt.get_width()-s.size(), fmt.get_fill())+s;
478 buf = s+string(fmt.get_width()-s.size(), fmt.get_fill());
487 void operator<<(LexicalConverter &c, char v)
489 Fmt::Type type = c.get_fmt().get_type();
491 c.result(int_to_str(v, c.get_fmt()));
493 c.result(string(1, v));
496 void operator<<(LexicalConverter &c, signed char v)
497 { c.result(int_to_str(v, c.get_fmt())); }
499 void operator<<(LexicalConverter &c, short v)
500 { c.result(int_to_str(v, c.get_fmt())); }
502 void operator<<(LexicalConverter &c, int v)
503 { c.result(int_to_str(v, c.get_fmt())); }
505 void operator<<(LexicalConverter &c, long v)
506 { c.result(int_to_str(v, c.get_fmt())); }
508 void operator<<(LexicalConverter &c, unsigned char v)
509 { c.result(int_to_str(v, c.get_fmt())); }
511 void operator<<(LexicalConverter &c, unsigned short v)
512 { c.result(int_to_str(v, c.get_fmt())); }
514 void operator<<(LexicalConverter &c, unsigned v)
515 { c.result(int_to_str(v, c.get_fmt())); }
517 void operator<<(LexicalConverter &c, unsigned long v)
518 { c.result(int_to_str(v, c.get_fmt())); }
521 void operator<<(LexicalConverter &c, long long v)
522 { c.result(int_to_str(v, c.get_fmt())); }
524 void operator<<(LexicalConverter &c, unsigned long long v)
525 { c.result(int_to_str(v, c.get_fmt())); }
528 void operator<<(LexicalConverter &c, bool v)
529 { c.result(bool_to_str(v, c.get_fmt())); }
531 void operator<<(LexicalConverter &c, float v)
532 { c.result(flt_to_str(v, c.get_fmt())); }
534 void operator<<(LexicalConverter &c, double v)
535 { c.result(flt_to_str(v, c.get_fmt())); }
537 void operator<<(LexicalConverter &c, long double v)
538 { c.result(flt_to_str(v, c.get_fmt())); }
540 void operator<<(LexicalConverter &c, const string &s)
541 { c.result(str_to_str(s, c.get_fmt())); }
543 void operator<<(LexicalConverter &c, const char *s)
544 { c.result(str_to_str(s, c.get_fmt())); }
546 void operator<<(LexicalConverter &c, const void *p)
547 { c.result(int_to_str(reinterpret_cast<unsigned long>(p), c.get_fmt())); }
552 void operator>>(const LexicalConverter &c, char &v)
554 if(c.get_fmt().get_type()==Fmt::NUM)
555 v = str_to_int<char>(c.get(), c.get_fmt());
558 const std::string &s = c.get();
560 throw lexical_error("conversion of '' to character");
562 throw lexical_error(format("conversion of '%s' to character", s));
567 void operator>>(const LexicalConverter &c, signed char &v)
568 { v = str_to_int<signed char>(c.get(), c.get_fmt()); }
570 void operator>>(const LexicalConverter &c, short &v)
571 { v = str_to_int<short>(c.get(), c.get_fmt()); }
573 void operator>>(const LexicalConverter &c, int &v)
574 { v = str_to_int<int>(c.get(), c.get_fmt()); }
576 void operator>>(const LexicalConverter &c, long &v)
577 { v = str_to_int<long>(c.get(), c.get_fmt()); }
579 void operator>>(const LexicalConverter &c, unsigned char &v)
580 { v = str_to_int<unsigned char>(c.get(), c.get_fmt()); }
582 void operator>>(const LexicalConverter &c, unsigned short &v)
583 { v = str_to_int<unsigned short>(c.get(), c.get_fmt()); }
585 void operator>>(const LexicalConverter &c, unsigned int &v)
586 { v = str_to_int<unsigned int>(c.get(), c.get_fmt()); }
588 void operator>>(const LexicalConverter &c, unsigned long &v)
589 { v = str_to_int<unsigned long>(c.get(), c.get_fmt()); }
592 void operator>>(const LexicalConverter &c, long long &v)
593 { v = str_to_int<long long>(c.get(), c.get_fmt()); }
595 void operator>>(const LexicalConverter &c, unsigned long long &v)
596 { v = str_to_int<unsigned long long>(c.get(), c.get_fmt()); }
599 void operator>>(const LexicalConverter &c, bool &v)
600 { v = str_to_bool(c.get()); }
602 void operator>>(const LexicalConverter &c, float &v)
603 { v = str_to_flt<float>(c.get(), c.get_fmt()); }
605 void operator>>(const LexicalConverter &c, double &v)
606 { v = str_to_flt<double>(c.get(), c.get_fmt()); }
608 void operator>>(const LexicalConverter &c, long double &v)
609 { v = str_to_flt<long double>(c.get(), c.get_fmt()); }
611 void operator>>(const LexicalConverter &c, string &s)
612 { s = str_to_str(c.get(), c.get_fmt()); }