// Copyright (c) 2009-2016 Vladimir Batov. // Use, modification and distribution are subject to the Boost Software License, // Version 1.0. See http://www.boost.org/LICENSE_1_0.txt. #ifndef BOOST_CONVERT_PRINTF_HPP #define BOOST_CONVERT_PRINTF_HPP #include #include #include #include #include #include #include namespace boost { namespace cnv { struct printf; }} struct boost::cnv::printf : boost::cnv::cnvbase { using this_type = boost::cnv::printf; using base_type = boost::cnv::cnvbase; using base_type::operator(); template cnv::range to_str(in_type value_in, char* buf) const { char const* fmt = pformat(pos()); int const num_chars = snprintf(buf, bufsize_, fmt, precision_, value_in); bool const success = num_chars < bufsize_; return cnv::range(buf, success ? (buf + num_chars) : buf); } template void str_to(cnv::range range, optional& result_out) const { out_type result = boost::make_default(); int const num_read = sscanf(&*range.begin(), format(pos()), &result); if (num_read == 1) result_out = result; } private: template int pos() const { using managed_types = boost::mpl::vector; using type_iterator = typename boost::mpl::find::type; using type_pos = typename type_iterator::pos; return type_pos::value; } char const* pformat(int pos) const { static char const* d_fmt[] = { "%.*f", "%.*f", "%.*d", "%.*u", "%.*hd", "%.*hu", "%.*ld", "%.*lu" }; // Must match managed_types static char const* x_fmt[] = { "%.*f", "%.*f", "%.*x", "%.*x", "%.*hx", "%.*hx", "%.*lx", "%.*lx" }; // Must match managed_types static char const* o_fmt[] = { "%.*f", "%.*f", "%.*o", "%.*o", "%.*ho", "%.*ho", "%.*lo", "%.*lo" }; // Must match managed_types char const* fmt = base_ == boost::cnv::base::dec ? d_fmt[pos] : base_ == boost::cnv::base::hex ? x_fmt[pos] : base_ == boost::cnv::base::oct ? o_fmt[pos] : (BOOST_ASSERT(0), nullptr); return fmt; } char const* format(int pos) const { static char const* d_fmt[] = { "%f", "%f", "%d", "%u", "%hd", "%hu", "%ld", "%lu" }; // Must match managed_types static char const* x_fmt[] = { "%f", "%f", "%x", "%x", "%hx", "%hx", "%lx", "%lx" }; // Must match managed_types static char const* o_fmt[] = { "%f", "%f", "%o", "%o", "%ho", "%ho", "%lo", "%lo" }; // Must match managed_types char const* fmt = base_ == boost::cnv::base::dec ? d_fmt[pos] : base_ == boost::cnv::base::hex ? x_fmt[pos] : base_ == boost::cnv::base::oct ? o_fmt[pos] : (BOOST_ASSERT(0), nullptr); return fmt; } }; #endif // BOOST_CONVERT_PRINTF_HPP