1 // Copyright (c) 2009-2016 Vladimir Batov.
2 // Use, modification and distribution are subject to the Boost Software License,
3 // Version 1.0. See http://www.boost.org/LICENSE_1_0.txt.
5 #ifndef BOOST_CONVERT_PRINTF_HPP
6 #define BOOST_CONVERT_PRINTF_HPP
8 #include <boost/convert/base.hpp>
9 #include <boost/make_default.hpp>
10 #include <boost/mpl/vector.hpp>
11 #include <boost/mpl/find.hpp>
12 #include <boost/range/as_literal.hpp>
16 namespace boost { namespace cnv
21 struct boost::cnv::printf : public boost::cnv::cnvbase<boost::cnv::printf>
23 typedef boost::cnv::printf this_type;
24 typedef boost::cnv::cnvbase<this_type> base_type;
26 using base_type::operator();
28 template<typename in_type>
30 to_str(in_type value_in, char* buf) const
32 char const* fmt = pformat(pos<in_type>());
33 int const num_chars = snprintf(buf, bufsize_, fmt, precision_, value_in);
34 bool const success = num_chars < bufsize_;
36 return cnv::range<char*>(buf, success ? (buf + num_chars) : buf);
38 template<typename string_type, typename out_type>
40 str_to(cnv::range<string_type> range, optional<out_type>& result_out) const
42 out_type result = boost::make_default<out_type>();
43 int const num_read = sscanf(&*range.begin(), format(pos<out_type>()), &result);
51 template<typename Type> int pos() const
53 typedef boost::mpl::vector<double, float,
55 short int, unsigned short int,
56 long int, unsigned long int
59 typedef typename boost::mpl::find<managed_types, Type>::type type_iterator;
60 typedef typename type_iterator::pos type_pos;
62 return type_pos::value;
65 char const* pformat(int pos) const
67 static char const* d_format[] = { "%.*f", "%.*f", "%.*d", "%.*u", "%.*hd", "%.*hu", "%.*ld", "%.*lu" }; // Must match managed_types
68 static char const* x_format[] = { "%.*f", "%.*f", "%.*x", "%.*x", "%.*hx", "%.*hx", "%.*lx", "%.*lx" }; // Must match managed_types
69 static char const* o_format[] = { "%.*f", "%.*f", "%.*o", "%.*o", "%.*ho", "%.*ho", "%.*lo", "%.*lo" }; // Must match managed_types
70 char const* format = base_ == 10 ? d_format[pos]
71 : base_ == 16 ? x_format[pos]
72 : base_ == 8 ? o_format[pos]
73 : (BOOST_ASSERT(0), (char const*) 0);
76 char const* format(int pos) const
78 static char const* d_format[] = { "%f", "%f", "%d", "%u", "%hd", "%hu", "%ld", "%lu" }; // Must match managed_types
79 static char const* x_format[] = { "%f", "%f", "%x", "%x", "%hx", "%hx", "%lx", "%lx" }; // Must match managed_types
80 static char const* o_format[] = { "%f", "%f", "%o", "%o", "%ho", "%ho", "%lo", "%lo" }; // Must match managed_types
81 char const* format = base_ == 10 ? d_format[pos]
82 : base_ == 16 ? x_format[pos]
83 : base_ == 8 ? o_format[pos]
84 : (BOOST_ASSERT(0), (char const*) 0);
89 #endif // BOOST_CONVERT_PRINTF_HPP