1 ///////////////////////////////////////////////////////////////////////////////
2 // Copyright Christopher Kormanyos 2014.
3 // Copyright John Maddock 2014.
4 // Copyright Paul Bristow 2014.
5 // Distributed under the Boost Software License,
6 // Version 1.0. (See accompanying file LICENSE_1_0.txt
7 // or copy at http://www.boost.org/LICENSE_1_0.txt)
10 // Implement quadruple-precision I/O stream operations.
12 #ifndef _BOOST_CSTDFLOAT_IOSTREAM_2014_02_15_HPP_
13 #define _BOOST_CSTDFLOAT_IOSTREAM_2014_02_15_HPP_
15 #include <boost/math/cstdfloat/cstdfloat_types.hpp>
16 #include <boost/math/cstdfloat/cstdfloat_limits.hpp>
17 #include <boost/math/cstdfloat/cstdfloat_cmath.hpp>
19 #if defined(BOOST_CSTDFLOAT_NO_LIBQUADMATH_CMATH)
20 #error You can not use <boost/math/cstdfloat/cstdfloat_iostream.hpp> with BOOST_CSTDFLOAT_NO_LIBQUADMATH_CMATH defined.
23 #if defined(BOOST_CSTDFLOAT_HAS_INTERNAL_FLOAT128_T) && defined(BOOST_MATH_USE_FLOAT128) && !defined(BOOST_CSTDFLOAT_NO_LIBQUADMATH_SUPPORT)
31 #include <boost/static_assert.hpp>
32 #include <boost/throw_exception.hpp>
37 // Forward declarations of quadruple-precision string functions.
38 extern "C" int quadmath_snprintf(char *str, size_t size, const char *format, ...) throw();
39 extern "C" boost::math::cstdfloat::detail::float_internal128_t strtoflt128(const char*, char **) throw();
43 template<typename char_type, class traits_type>
44 inline std::basic_ostream<char_type, traits_type>& operator<<(std::basic_ostream<char_type, traits_type>& os, const boost::math::cstdfloat::detail::float_internal128_t& x)
46 std::basic_ostringstream<char_type, traits_type> ostr;
47 ostr.flags(os.flags());
48 ostr.imbue(os.getloc());
49 ostr.precision(os.precision());
53 const int my_prec = static_cast<int>(os.precision());
54 const int my_digits = ((my_prec == 0) ? 36 : my_prec);
56 const std::ios_base::fmtflags my_flags = os.flags();
58 char my_format_string[8U];
60 std::size_t my_format_string_index = 0U;
62 my_format_string[my_format_string_index] = '%';
63 ++my_format_string_index;
65 if(my_flags & std::ios_base::showpos) { my_format_string[my_format_string_index] = '+'; ++my_format_string_index; }
66 if(my_flags & std::ios_base::showpoint) { my_format_string[my_format_string_index] = '#'; ++my_format_string_index; }
68 my_format_string[my_format_string_index + 0U] = '.';
69 my_format_string[my_format_string_index + 1U] = '*';
70 my_format_string[my_format_string_index + 2U] = 'Q';
72 my_format_string_index += 3U;
74 char the_notation_char;
76 if (my_flags & std::ios_base::scientific) { the_notation_char = 'e'; }
77 else if(my_flags & std::ios_base::fixed) { the_notation_char = 'f'; }
78 else { the_notation_char = 'g'; }
80 my_format_string[my_format_string_index + 0U] = the_notation_char;
81 my_format_string[my_format_string_index + 1U] = 0;
83 const int v = ::quadmath_snprintf(my_buffer,
84 static_cast<int>(sizeof(my_buffer)),
89 if(v < 0) { BOOST_THROW_EXCEPTION(std::runtime_error("Formatting of boost::float128_t failed internally in quadmath_snprintf().")); }
91 if(v >= static_cast<int>(sizeof(my_buffer) - 1U))
93 // Evidently there is a really long floating-point string here,
94 // such as a small decimal representation in non-scientific notation.
95 // So we have to use dynamic memory allocation for the output
98 char* my_buffer2 = static_cast<char*>(0U);
100 #ifndef BOOST_NO_EXCEPTIONS
104 my_buffer2 = new char[v + 3];
105 #ifndef BOOST_NO_EXCEPTIONS
107 catch(const std::bad_alloc&)
109 BOOST_THROW_EXCEPTION(std::runtime_error("Formatting of boost::float128_t failed while allocating memory."));
112 const int v2 = ::quadmath_snprintf(my_buffer2,
120 BOOST_THROW_EXCEPTION(std::runtime_error("Formatting of boost::float128_t failed."));
123 static_cast<void>(ostr << my_buffer2);
125 delete [] my_buffer2;
129 static_cast<void>(ostr << my_buffer);
132 return (os << ostr.str());
135 template<typename char_type, class traits_type>
136 inline std::basic_istream<char_type, traits_type>& operator>>(std::basic_istream<char_type, traits_type>& is, boost::math::cstdfloat::detail::float_internal128_t& x)
140 static_cast<void>(is >> str);
144 x = strtoflt128(str.c_str(), &p_end);
146 if(static_cast<std::ptrdiff_t>(p_end - str.c_str()) != static_cast<std::ptrdiff_t>(str.length()))
148 for(std::string::const_reverse_iterator it = str.rbegin(); it != str.rend(); ++it)
150 static_cast<void>(is.putback(*it));
153 is.setstate(ios_base::failbit);
155 BOOST_THROW_EXCEPTION(std::runtime_error("Unable to interpret input string as a boost::float128_t"));
162 // #elif defined(__GNUC__)
163 #elif defined(BOOST_INTEL)
165 // The section for I/O stream support for the ICC compiler is particularly
166 // long, because these functions must be painstakingly synthesized from
167 // manually-written routines (ICC does not support I/O stream operations
168 // for its _Quad type).
170 // The following string-extraction routines are based on the methodology
171 // used in Boost.Multiprecision by John Maddock and Christopher Kormanyos.
172 // This methodology has been slightly modified here for boost::float128_t.
176 #include <boost/lexical_cast.hpp>
178 namespace boost { namespace math { namespace cstdfloat { namespace detail {
180 template<class string_type>
181 void format_float_string(string_type& str,
184 const std::ios_base::fmtflags f,
187 typedef typename string_type::size_type size_type;
189 const bool scientific = ((f & std::ios_base::scientific) == std::ios_base::scientific);
190 const bool fixed = ((f & std::ios_base::fixed) == std::ios_base::fixed);
191 const bool showpoint = ((f & std::ios_base::showpoint) == std::ios_base::showpoint);
192 const bool showpos = ((f & std::ios_base::showpos) == std::ios_base::showpos);
194 const bool b_neg = ((str.size() != 0U) && (str[0] == '-'));
203 digits = static_cast<int>((std::max)(str.size(), size_type(16)));
206 if(iszero || str.empty() || (str.find_first_not_of('0') == string_type::npos))
208 // We will be printing zero, even though the value might not
209 // actually be zero (it just may have been rounded to zero).
212 if(scientific || fixed)
215 str.append(size_type(digits), '0');
229 str.append(size_type(digits - 1), '0');
236 str.insert(0U, 1U, '-');
240 str.insert(0U, 1U, '+');
246 if(!fixed && !scientific && !showpoint)
248 // Suppress trailing zeros.
249 typename string_type::iterator pos = str.end();
251 while(pos != str.begin() && *--pos == '0') { ; }
258 str.erase(pos, str.end());
265 else if(!fixed || (my_exp >= 0))
267 // Pad out the end with zero's if we need to.
269 int chars = static_cast<int>(str.size());
270 chars = digits - chars;
279 str.append(static_cast<size_type>(chars), '0');
283 if(fixed || (!scientific && (my_exp >= -4) && (my_exp < digits)))
285 if((1 + my_exp) > static_cast<int>(str.size()))
287 // Just pad out the end with zeros.
288 str.append(static_cast<size_type>((1 + my_exp) - static_cast<int>(str.size())), '0');
290 if(showpoint || fixed)
295 else if(my_exp + 1 < static_cast<int>(str.size()))
299 str.insert(0U, static_cast<size_type>(-1 - my_exp), '0');
300 str.insert(0U, "0.");
304 // Insert the decimal point:
305 str.insert(static_cast<size_type>(my_exp + 1), 1, '.');
308 else if(showpoint || fixed) // we have exactly the digits we require to left of the point
315 // We may need to add trailing zeros.
316 int l = static_cast<int>(str.find('.') + 1U);
317 l = digits - (static_cast<int>(str.size()) - l);
321 str.append(size_type(l), '0');
327 // Scientific format:
328 if(showpoint || (str.size() > 1))
330 str.insert(1U, 1U, '.');
334 string_type e = boost::lexical_cast<string_type>(std::abs(my_exp));
338 e.insert(0U, 2U - e.size(), '0');
343 e.insert(0U, 1U, '-');
347 e.insert(0U, 1U, '+');
355 str.insert(0U, 1U, '-');
359 str.insert(0U, 1U, '+');
363 template<class float_type, class type_a> inline void eval_convert_to(type_a* pa, const float_type& cb) { *pa = static_cast<type_a>(cb); }
364 template<class float_type, class type_a> inline void eval_add (float_type& b, const type_a& a) { b += a; }
365 template<class float_type, class type_a> inline void eval_subtract (float_type& b, const type_a& a) { b -= a; }
366 template<class float_type, class type_a> inline void eval_multiply (float_type& b, const type_a& a) { b *= a; }
367 template<class float_type> inline void eval_multiply (float_type& b, const float_type& cb, const float_type& cb2) { b = (cb * cb2); }
368 template<class float_type, class type_a> inline void eval_divide (float_type& b, const type_a& a) { b /= a; }
369 template<class float_type> inline void eval_log10 (float_type& b, const float_type& cb) { b = std::log10(cb); }
370 template<class float_type> inline void eval_floor (float_type& b, const float_type& cb) { b = std::floor(cb); }
372 inline void round_string_up_at(std::string& s, int pos, int& expon)
374 // This subroutine rounds up a string representation of a
375 // number at the given position pos.
379 s.insert(0U, 1U, '1');
380 s.erase(s.size() - 1U);
383 else if(s[pos] == '9')
386 round_string_up_at(s, pos - 1, expon);
390 if((pos == 0) && (s[pos] == '0') && (s.size() == 1))
399 template<class float_type>
400 std::string convert_to_string(float_type& x,
401 std::streamsize digits,
402 const std::ios_base::fmtflags f)
404 const bool isneg = (x < 0);
405 const bool iszero = ((!isneg) ? bool(+x < (std::numeric_limits<float_type>::min)())
406 : bool(-x < (std::numeric_limits<float_type>::min)()));
407 const bool isnan = (x != x);
408 const bool isinf = ((!isneg) ? bool(+x > (std::numeric_limits<float_type>::max)())
409 : bool(-x > (std::numeric_limits<float_type>::max)()));
413 if(digits <= 0) { digits = std::numeric_limits<float_type>::max_digits10; }
415 const int org_digits = static_cast<int>(digits);
431 return ((f & std::ios_base::showpos) == std::ios_base::showpos) ? "+inf" : "inf";
440 // Start by figuring out the base-10 exponent.
441 if(isneg) { x = -x; }
448 eval_convert_to(&expon, t);
450 if(-expon > std::numeric_limits<float_type>::max_exponent10 - 3)
454 const float_type t2 = boost::math::cstdfloat::detail::pown(ten, e);
456 eval_multiply(t, t2, x);
457 eval_multiply(t, t2);
461 eval_multiply(t, ten);
466 t = boost::math::cstdfloat::detail::pown(ten, -expon);
470 // Make sure that the value lies between [1, 10), and adjust if not.
473 eval_multiply(t, 10);
487 // Adjust the number of digits required based on formatting options.
488 if(((f & std::ios_base::fixed) == std::ios_base::fixed) && (expon != -1))
490 digits += (expon + 1);
493 if((f & std::ios_base::scientific) == std::ios_base::scientific)
498 // Extract the base-10 digits one at a time.
499 for(int i = 0; i < digits; ++i)
501 eval_floor(digit, t);
502 eval_convert_to(&cdigit, digit);
504 result += static_cast<char>('0' + cdigit);
506 eval_subtract(t, digit);
507 eval_multiply(t, ten);
510 // Possibly round the result.
513 eval_floor(digit, t);
514 eval_convert_to(&cdigit, digit);
515 eval_subtract(t, digit);
517 if((cdigit == 5) && (t == 0))
519 // Use simple bankers rounding.
521 if((static_cast<int>(*result.rbegin() - '0') & 1) != 0)
523 round_string_up_at(result, static_cast<int>(result.size() - 1U), expon);
528 round_string_up_at(result, static_cast<int>(result.size() - 1), expon);
533 while((result.size() > static_cast<std::string::size_type>(digits)) && result.size())
535 // We may get here as a result of rounding.
537 if(result.size() > 1U)
539 result.erase(result.size() - 1U);
545 --expon; // so we put less padding in the result.
558 result.insert(0U, 1U, '-');
561 format_float_string(result, expon, org_digits, f, iszero);
566 template <class float_type>
567 bool convert_from_string(float_type& value, const char* p)
571 if((p == static_cast<const char*>(0U)) || (*p == static_cast<char>(0)))
577 bool is_neg_expon = false;
579 BOOST_CONSTEXPR_OR_CONST int ten = 10;
584 BOOST_CONSTEXPR_OR_CONST int max_digits = std::numeric_limits<float_type>::max_digits10 + 1;
586 if(*p == static_cast<char>('+'))
590 else if(*p == static_cast<char>('-'))
596 const bool isnan = ((std::strcmp(p, "nan") == 0) || (std::strcmp(p, "NaN") == 0) || (std::strcmp(p, "NAN") == 0));
600 eval_divide(value, 0);
610 const bool isinf = ((std::strcmp(p, "inf") == 0) || (std::strcmp(p, "Inf") == 0) || (std::strcmp(p, "INF") == 0));
615 eval_divide(value, 0);
625 // Grab all the leading digits before the decimal point.
626 while(std::isdigit(*p))
628 eval_multiply(value, ten);
629 eval_add(value, static_cast<int>(*p - '0'));
634 if(*p == static_cast<char>('.'))
636 // Grab everything after the point, stop when we've seen
637 // enough digits, even if there are actually more available.
641 while(std::isdigit(*p))
643 eval_multiply(value, ten);
644 eval_add(value, static_cast<int>(*p - '0'));
648 if(++digits_seen > max_digits)
654 while(std::isdigit(*p))
660 // Parse the exponent.
661 if((*p == static_cast<char>('e')) || (*p == static_cast<char>('E')))
665 if(*p == static_cast<char>('+'))
669 else if(*p == static_cast<char>('-'))
677 while(std::isdigit(*p))
694 // Scale by 10^expon. Note that 10^expon can be outside the range
695 // of our number type, even though the result is within range.
696 // If that looks likely, then split the calculation in two parts.
700 if(expon > (std::numeric_limits<float_type>::min_exponent10 + 2))
702 t = boost::math::cstdfloat::detail::pown(t, expon);
703 eval_multiply(value, t);
707 t = boost::math::cstdfloat::detail::pown(t, (expon + digits_seen + 1));
708 eval_multiply(value, t);
710 t = boost::math::cstdfloat::detail::pown(t, (-digits_seen - 1));
711 eval_multiply(value, t);
720 return (*p == static_cast<char>(0));
722 } } } } // boost::math::cstdfloat::detail
726 template<typename char_type, class traits_type>
727 inline std::basic_ostream<char_type, traits_type>& operator<<(std::basic_ostream<char_type, traits_type>& os, const boost::math::cstdfloat::detail::float_internal128_t& x)
729 boost::math::cstdfloat::detail::float_internal128_t non_const_x = x;
731 const std::string str = boost::math::cstdfloat::detail::convert_to_string(non_const_x,
735 std::basic_ostringstream<char_type, traits_type> ostr;
736 ostr.flags(os.flags());
737 ostr.imbue(os.getloc());
738 ostr.precision(os.precision());
740 static_cast<void>(ostr << str);
742 return (os << ostr.str());
745 template<typename char_type, class traits_type>
746 inline std::basic_istream<char_type, traits_type>& operator>>(std::basic_istream<char_type, traits_type>& is, boost::math::cstdfloat::detail::float_internal128_t& x)
750 static_cast<void>(is >> str);
752 const bool conversion_is_ok = boost::math::cstdfloat::detail::convert_from_string(x, str.c_str());
754 if(false == conversion_is_ok)
756 for(std::string::const_reverse_iterator it = str.rbegin(); it != str.rend(); ++it)
758 static_cast<void>(is.putback(*it));
761 is.setstate(ios_base::failbit);
763 BOOST_THROW_EXCEPTION(std::runtime_error("Unable to interpret input string as a boost::float128_t"));
770 #endif // Use __GNUC__ or BOOST_INTEL libquadmath
772 #endif // Not BOOST_CSTDFLOAT_NO_LIBQUADMATH_SUPPORT (i.e., the user would like to have libquadmath support)
774 #endif // _BOOST_CSTDFLOAT_IOSTREAM_2014_02_15_HPP_