2 * Copyright 2014 Facebook, Inc.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
18 * Converts anything to anything, with an emphasis on performance and
21 * @author Andrei Alexandrescu (andrei.alexandrescu@fb.com)
24 #ifndef FOLLY_BASE_CONV_H_
25 #define FOLLY_BASE_CONV_H_
27 #include <folly/FBString.h>
28 #include <folly/Likely.h>
29 #include <folly/Preprocessor.h>
30 #include <folly/Range.h>
32 #include <boost/implicit_cast.hpp>
34 #include <type_traits>
43 // V8 JavaScript implementation
44 #include <double-conversion/double-conversion.h>
46 #define FOLLY_RANGE_CHECK_STRINGIZE(x) #x
47 #define FOLLY_RANGE_CHECK_STRINGIZE2(x) FOLLY_RANGE_CHECK_STRINGIZE(x)
49 #define FOLLY_RANGE_CHECK(condition, message, src) \
50 ((condition) ? (void)0 : throw std::range_error( \
51 (std::string(__FILE__ "(" FOLLY_RANGE_CHECK_STRINGIZE2(__LINE__) "): ") \
52 + (message) + ": '" + (src) + "'").c_str()))
54 #define FOLLY_RANGE_CHECK_BEGIN_END(condition, message, b, e) \
55 FOLLY_RANGE_CHECK(condition, message, std::string((b), (e) - (b)))
57 #define FOLLY_RANGE_CHECK_STRINGPIECE(condition, message, sp) \
58 FOLLY_RANGE_CHECK(condition, message, std::string((sp).data(), (sp).size()))
63 * The identity conversion function.
64 * to<T>(T) returns itself for all types T.
66 template <class Tgt, class Src>
67 typename std::enable_if<std::is_same<Tgt, Src>::value, Tgt>::type
68 to(const Src & value) {
72 template <class Tgt, class Src>
73 typename std::enable_if<std::is_same<Tgt, Src>::value, Tgt>::type
75 return std::move(value);
78 /*******************************************************************************
79 * Integral to integral
80 ******************************************************************************/
83 * Checked conversion from integral to integral. The checks are only
84 * performed when meaningful, e.g. conversion from int to long goes
87 template <class Tgt, class Src>
88 typename std::enable_if<
89 std::is_integral<Src>::value
90 && std::is_integral<Tgt>::value
91 && !std::is_same<Tgt, Src>::value,
93 to(const Src & value) {
94 /* static */ if (std::numeric_limits<Tgt>::max()
95 < std::numeric_limits<Src>::max()) {
97 (!greater_than<Tgt, std::numeric_limits<Tgt>::max()>(value)),
98 "Overflow", std::to_string(value)
101 /* static */ if (std::is_signed<Src>::value &&
102 (!std::is_signed<Tgt>::value || sizeof(Src) > sizeof(Tgt))) {
104 (!less_than<Tgt, std::numeric_limits<Tgt>::min()>(value)),
105 "Negative overflow", std::to_string(value)
108 return static_cast<Tgt>(value);
111 /*******************************************************************************
112 * Floating point to floating point
113 ******************************************************************************/
115 template <class Tgt, class Src>
116 typename std::enable_if<
117 std::is_floating_point<Tgt>::value
118 && std::is_floating_point<Src>::value
119 && !std::is_same<Tgt, Src>::value,
121 to(const Src & value) {
122 /* static */ if (std::numeric_limits<Tgt>::max() <
123 std::numeric_limits<Src>::max()) {
124 FOLLY_RANGE_CHECK(value <= std::numeric_limits<Tgt>::max(),
125 "Overflow", std::to_string(value));
126 FOLLY_RANGE_CHECK(value >= -std::numeric_limits<Tgt>::max(),
127 "Negative overflow", std::to_string(value));
129 return boost::implicit_cast<Tgt>(value);
132 /*******************************************************************************
134 ******************************************************************************/
139 const T& getLastElement(const T & v) {
143 template <class T, class... Ts>
144 typename std::tuple_element<
146 std::tuple<T, Ts...> >::type const&
147 getLastElement(const T& v, const Ts&... vs) {
148 return getLastElement(vs...);
151 // This class exists to specialize away std::tuple_element in the case where we
152 // have 0 template arguments. Without this, Clang/libc++ will blow a
153 // static_assert even if tuple_element is protected by an enable_if.
154 template <class... Ts>
155 struct last_element {
156 typedef typename std::enable_if<
158 typename std::tuple_element<
159 sizeof...(Ts) - 1, std::tuple<Ts...>
164 struct last_element<> {
168 } // namespace detail
170 /*******************************************************************************
171 * Conversions from integral types to string types.
172 ******************************************************************************/
174 #if FOLLY_HAVE_INT128_T
177 template <typename IntegerType>
178 constexpr unsigned int
180 return ceil((double(sizeof(IntegerType) * CHAR_BIT) * M_LN2) / M_LN10);
184 unsafeTelescope128(char * buffer, size_t room, unsigned __int128 x) {
185 typedef unsigned __int128 Usrc;
188 while (x >= (Usrc(1) << 64)) { // Using 128-bit division while needed
189 const auto y = x / 10;
190 const auto digit = x % 10;
192 buffer[p--] = '0' + digit;
196 uint64_t xx = x; // Moving to faster 64-bit division thereafter
199 const auto y = xx / 10ULL;
200 const auto digit = xx % 10ULL;
202 buffer[p--] = '0' + digit;
206 buffer[p] = '0' + xx;
215 * Returns the number of digits in the base 10 representation of an
216 * uint64_t. Useful for preallocating buffers and such. It's also used
217 * internally, see below. Measurements suggest that defining a
218 * separate overload for 32-bit integers is not worthwhile.
221 inline uint32_t digits10(uint64_t v) {
224 if (LIKELY(v < 10)) return result;
225 if (LIKELY(v < 100)) return result + 1;
226 if (LIKELY(v < 1000)) return result + 2;
227 if (LIKELY(v < 10000)) return result + 3;
228 // Skip ahead by 4 orders of magnitude
235 * Copies the ASCII base 10 representation of v into buffer and
236 * returns the number of bytes written. Does NOT append a \0. Assumes
237 * the buffer points to digits10(v) bytes of valid memory. Note that
238 * uint64 needs at most 20 bytes, uint32_t needs at most 10 bytes,
239 * uint16_t needs at most 5 bytes, and so on. Measurements suggest
240 * that defining a separate overload for 32-bit integers is not
243 * This primitive is unsafe because it makes the size assumption and
244 * because it does not add a terminating \0.
247 inline uint32_t uint64ToBufferUnsafe(uint64_t v, char *const buffer) {
248 auto const result = digits10(v);
249 // WARNING: using size_t or pointer arithmetic for pos slows down
250 // the loop below 20x. This is because several 32-bit ops can be
251 // done in parallel, but only fewer 64-bit ones.
252 uint32_t pos = result - 1;
254 // Keep these together so a peephole optimization "sees" them and
255 // computes them in one shot.
256 auto const q = v / 10;
257 auto const r = static_cast<uint32_t>(v % 10);
258 buffer[pos--] = '0' + r;
261 // Last digit is trivial to handle
262 buffer[pos] = static_cast<uint32_t>(v) + '0';
267 * A single char gets appended.
270 void toAppend(char value, Tgt * result) {
275 constexpr typename std::enable_if<
276 std::is_same<T, char>::value,
278 estimateSpaceNeeded(T) {
283 * Ubiquitous helper template for writing string appenders
285 template <class T> struct IsSomeString {
286 enum { value = std::is_same<T, std::string>::value
287 || std::is_same<T, fbstring>::value };
291 * Everything implicitly convertible to const char* gets appended.
293 template <class Tgt, class Src>
294 typename std::enable_if<
295 std::is_convertible<Src, const char*>::value
296 && IsSomeString<Tgt>::value>::type
297 toAppend(Src value, Tgt * result) {
298 // Treat null pointers like an empty string, as in:
299 // operator<<(std::ostream&, const char*).
300 const char* c = value;
302 result->append(value);
307 typename std::enable_if<
308 std::is_convertible<Src, const char*>::value,
310 estimateSpaceNeeded(Src value) {
311 const char *c = value;
313 return folly::StringPiece(value).size();
319 typename std::enable_if<
320 (std::is_convertible<Src, folly::StringPiece>::value ||
321 IsSomeString<Src>::value) &&
322 !std::is_convertible<Src, const char*>::value,
324 estimateSpaceNeeded(Src value) {
325 return folly::StringPiece(value).size();
329 typename std::enable_if<
330 std::is_pointer<Src>::value &&
331 IsSomeString<std::remove_pointer<Src>>::value,
333 estimateSpaceNeeded(Src value) {
334 return value->size();
338 * Strings get appended, too.
340 template <class Tgt, class Src>
341 typename std::enable_if<
342 IsSomeString<Src>::value && IsSomeString<Tgt>::value>::type
343 toAppend(const Src& value, Tgt * result) {
344 result->append(value);
348 * and StringPiece objects too
351 typename std::enable_if<
352 IsSomeString<Tgt>::value>::type
353 toAppend(StringPiece value, Tgt * result) {
354 result->append(value.data(), value.size());
358 * There's no implicit conversion from fbstring to other string types,
359 * so make a specialization.
362 typename std::enable_if<
363 IsSomeString<Tgt>::value>::type
364 toAppend(const fbstring& value, Tgt * result) {
365 result->append(value.data(), value.size());
368 #if FOLLY_HAVE_INT128_T
370 * Special handling for 128 bit integers.
375 toAppend(__int128 value, Tgt * result) {
376 typedef unsigned __int128 Usrc;
377 char buffer[detail::digitsEnough<unsigned __int128>() + 1];
381 p = detail::unsafeTelescope128(buffer, sizeof(buffer), Usrc(-value));
384 p = detail::unsafeTelescope128(buffer, sizeof(buffer), value);
387 result->append(buffer + p, buffer + sizeof(buffer));
392 toAppend(unsigned __int128 value, Tgt * result) {
393 char buffer[detail::digitsEnough<unsigned __int128>()];
396 p = detail::unsafeTelescope128(buffer, sizeof(buffer), value);
398 result->append(buffer + p, buffer + sizeof(buffer));
402 constexpr typename std::enable_if<
403 std::is_same<T, __int128>::value,
405 estimateSpaceNeeded(T) {
406 return detail::digitsEnough<__int128>();
410 constexpr typename std::enable_if<
411 std::is_same<T, unsigned __int128>::value,
413 estimateSpaceNeeded(T) {
414 return detail::digitsEnough<unsigned __int128>();
420 * int32_t and int64_t to string (by appending) go through here. The
421 * result is APPENDED to a preexisting string passed as the second
422 * parameter. This should be efficient with fbstring because fbstring
423 * incurs no dynamic allocation below 23 bytes and no number has more
424 * than 22 bytes in its textual representation (20 for digits, one for
425 * sign, one for the terminating 0).
427 template <class Tgt, class Src>
428 typename std::enable_if<
429 std::is_integral<Src>::value && std::is_signed<Src>::value &&
430 IsSomeString<Tgt>::value && sizeof(Src) >= 4>::type
431 toAppend(Src value, Tgt * result) {
434 result->push_back('-');
435 result->append(buffer, uint64ToBufferUnsafe(-uint64_t(value), buffer));
437 result->append(buffer, uint64ToBufferUnsafe(value, buffer));
442 typename std::enable_if<
443 std::is_integral<Src>::value && std::is_signed<Src>::value
444 && sizeof(Src) >= 4 && sizeof(Src) < 16,
446 estimateSpaceNeeded(Src value) {
448 return 1 + digits10(static_cast<uint64_t>(-value));
451 return digits10(static_cast<uint64_t>(value));
455 * As above, but for uint32_t and uint64_t.
457 template <class Tgt, class Src>
458 typename std::enable_if<
459 std::is_integral<Src>::value && !std::is_signed<Src>::value
460 && IsSomeString<Tgt>::value && sizeof(Src) >= 4>::type
461 toAppend(Src value, Tgt * result) {
463 result->append(buffer, buffer + uint64ToBufferUnsafe(value, buffer));
467 typename std::enable_if<
468 std::is_integral<Src>::value && !std::is_signed<Src>::value
469 && sizeof(Src) >= 4 && sizeof(Src) < 16,
471 estimateSpaceNeeded(Src value) {
472 return digits10(value);
476 * All small signed and unsigned integers to string go through 32-bit
477 * types int32_t and uint32_t, respectively.
479 template <class Tgt, class Src>
480 typename std::enable_if<
481 std::is_integral<Src>::value
482 && IsSomeString<Tgt>::value && sizeof(Src) < 4>::type
483 toAppend(Src value, Tgt * result) {
485 std::conditional<std::is_signed<Src>::value, int64_t, uint64_t>::type
487 toAppend<Tgt>(static_cast<Intermediate>(value), result);
491 typename std::enable_if<
492 std::is_integral<Src>::value
494 && !std::is_same<Src, char>::value,
496 estimateSpaceNeeded(Src value) {
498 std::conditional<std::is_signed<Src>::value, int64_t, uint64_t>::type
500 return estimateSpaceNeeded(static_cast<Intermediate>(value));
503 #if defined(__clang__) || __GNUC_PREREQ(4, 7)
504 // std::underlying_type became available by gcc 4.7.0
507 * Enumerated values get appended as integers.
509 template <class Tgt, class Src>
510 typename std::enable_if<
511 std::is_enum<Src>::value && IsSomeString<Tgt>::value>::type
512 toAppend(Src value, Tgt * result) {
514 static_cast<typename std::underlying_type<Src>::type>(value), result);
518 typename std::enable_if<
519 std::is_enum<Src>::value, size_t>::type
520 estimateSpaceNeeded(Src value) {
521 return estimateSpaceNeeded(
522 static_cast<typename std::underlying_type<Src>::type>(value));
528 * Enumerated values get appended as integers.
530 template <class Tgt, class Src>
531 typename std::enable_if<
532 std::is_enum<Src>::value && IsSomeString<Tgt>::value>::type
533 toAppend(Src value, Tgt * result) {
534 /* static */ if (Src(-1) < 0) {
535 /* static */ if (sizeof(Src) <= sizeof(int)) {
536 toAppend(static_cast<int>(value), result);
538 toAppend(static_cast<long>(value), result);
541 /* static */ if (sizeof(Src) <= sizeof(int)) {
542 toAppend(static_cast<unsigned int>(value), result);
544 toAppend(static_cast<unsigned long>(value), result);
550 typename std::enable_if<
551 std::is_enum<Src>::value, size_t>::type
552 estimateSpaceNeeded(Src value) {
553 /* static */ if (Src(-1) < 0) {
554 /* static */ if (sizeof(Src) <= sizeof(int)) {
555 return estimateSpaceNeeded(static_cast<int>(value));
557 return estimateSpaceNeeded(static_cast<long>(value));
560 /* static */ if (sizeof(Src) <= sizeof(int)) {
561 return estimateSpaceNeeded(static_cast<unsigned int>(value));
563 return estimateSpaceNeeded(static_cast<unsigned long>(value));
568 #endif // gcc 4.7 onwards
570 /*******************************************************************************
571 * Conversions from floating-point types to string types.
572 ******************************************************************************/
575 constexpr int kConvMaxDecimalInShortestLow = -6;
576 constexpr int kConvMaxDecimalInShortestHigh = 21;
579 /** Wrapper around DoubleToStringConverter **/
580 template <class Tgt, class Src>
581 typename std::enable_if<
582 std::is_floating_point<Src>::value
583 && IsSomeString<Tgt>::value>::type
587 double_conversion::DoubleToStringConverter::DtoaMode mode,
588 unsigned int numDigits) {
589 using namespace double_conversion;
590 DoubleToStringConverter
591 conv(DoubleToStringConverter::NO_FLAGS,
592 "infinity", "NaN", 'E',
593 detail::kConvMaxDecimalInShortestLow,
594 detail::kConvMaxDecimalInShortestHigh,
595 6, // max leading padding zeros
596 1); // max trailing padding zeros
598 StringBuilder builder(buffer, sizeof(buffer));
600 case DoubleToStringConverter::SHORTEST:
601 conv.ToShortest(value, &builder);
603 case DoubleToStringConverter::FIXED:
604 conv.ToFixed(value, numDigits, &builder);
607 CHECK(mode == DoubleToStringConverter::PRECISION);
608 conv.ToPrecision(value, numDigits, &builder);
611 const size_t length = builder.position();
613 result->append(buffer, length);
617 * As above, but for floating point
619 template <class Tgt, class Src>
620 typename std::enable_if<
621 std::is_floating_point<Src>::value
622 && IsSomeString<Tgt>::value>::type
623 toAppend(Src value, Tgt * result) {
625 value, result, double_conversion::DoubleToStringConverter::SHORTEST, 0);
629 * Upper bound of the length of the output from
630 * DoubleToStringConverter::ToShortest(double, StringBuilder*),
631 * as used in toAppend(double, string*).
634 typename std::enable_if<
635 std::is_floating_point<Src>::value, size_t>::type
636 estimateSpaceNeeded(Src value) {
637 // kBase10MaximalLength is 17. We add 1 for decimal point,
638 // e.g. 10.0/9 is 17 digits and 18 characters, including the decimal point.
639 constexpr int kMaxMantissaSpace =
640 double_conversion::DoubleToStringConverter::kBase10MaximalLength + 1;
641 // strlen("E-") + digits10(numeric_limits<double>::max_exponent10)
642 constexpr int kMaxExponentSpace = 2 + 3;
643 static const int kMaxPositiveSpace = std::max({
644 // E.g. 1.1111111111111111E-100.
645 kMaxMantissaSpace + kMaxExponentSpace,
646 // E.g. 0.000001.1111111111111111, if kConvMaxDecimalInShortestLow is -6.
647 kMaxMantissaSpace - detail::kConvMaxDecimalInShortestLow,
648 // If kConvMaxDecimalInShortestHigh is 21, then 1e21 is the smallest
649 // number > 1 which ToShortest outputs in exponential notation,
650 // so 21 is the longest non-exponential number > 1.
651 detail::kConvMaxDecimalInShortestHigh
653 return kMaxPositiveSpace + (value < 0); // +1 for minus sign, if negative
657 * This can be specialized, together with adding specialization
658 * for estimateSpaceNeed for your type, so that we allocate
659 * as much as you need instead of the default
662 struct HasLengthEstimator : std::false_type {};
665 constexpr typename std::enable_if<
666 !std::is_fundamental<Src>::value
667 #ifdef FOLLY_HAVE_INT128_T
668 // On OSX 10.10, is_fundamental<__int128> is false :-O
669 && !std::is_same<__int128, Src>::value
670 && !std::is_same<unsigned __int128, Src>::value
672 && !IsSomeString<Src>::value
673 && !std::is_convertible<Src, const char*>::value
674 && !std::is_convertible<Src, StringPiece>::value
675 && !std::is_enum<Src>::value
676 && !HasLengthEstimator<Src>::value,
678 estimateSpaceNeeded(const Src&) {
679 return sizeof(Src) + 1; // dumbest best effort ever?
684 inline size_t estimateSpaceToReserve(size_t sofar) {
688 template <class T, class... Ts>
689 size_t estimateSpaceToReserve(size_t sofar, const T& v, const Ts&... vs) {
690 return estimateSpaceToReserve(sofar + estimateSpaceNeeded(v), vs...);
694 size_t estimateSpaceToReserve(size_t sofar, const T& v) {
695 return sofar + estimateSpaceNeeded(v);
699 void reserveInTarget(const Ts&...vs) {
700 getLastElement(vs...)->reserve(estimateSpaceToReserve(0, vs...));
703 template<class Delimiter, class...Ts>
704 void reserveInTargetDelim(const Delimiter& d, const Ts&...vs) {
705 static_assert(sizeof...(vs) >= 2, "Needs at least 2 args");
706 size_t fordelim = (sizeof...(vs) - 2) * estimateSpaceToReserve(0, d);
707 getLastElement(vs...)->reserve(estimateSpaceToReserve(fordelim, vs...));
711 * Variadic base case: append one element
713 template <class T, class Tgt>
714 typename std::enable_if<
715 IsSomeString<typename std::remove_pointer<Tgt>::type>
717 toAppendStrImpl(const T& v, Tgt result) {
721 template <class T, class... Ts>
722 typename std::enable_if<sizeof...(Ts) >= 2
724 typename std::remove_pointer<
725 typename detail::last_element<Ts...>::type
726 >::type>::value>::type
727 toAppendStrImpl(const T& v, const Ts&... vs) {
728 toAppend(v, getLastElement(vs...));
729 toAppendStrImpl(vs...);
732 template <class Delimiter, class T, class Tgt>
733 typename std::enable_if<
734 IsSomeString<typename std::remove_pointer<Tgt>::type>
736 toAppendDelimStrImpl(const Delimiter& delim, const T& v, Tgt result) {
740 template <class Delimiter, class T, class... Ts>
741 typename std::enable_if<sizeof...(Ts) >= 2
743 typename std::remove_pointer<
744 typename detail::last_element<Ts...>::type
745 >::type>::value>::type
746 toAppendDelimStrImpl(const Delimiter& delim, const T& v, const Ts&... vs) {
747 // we are really careful here, calling toAppend with just one element does
748 // not try to estimate space needed (as we already did that). If we call
749 // toAppend(v, delim, ....) we would do unnecesary size calculation
750 toAppend(v, detail::getLastElement(vs...));
751 toAppend(delim, detail::getLastElement(vs...));
752 toAppendDelimStrImpl(delim, vs...);
758 * Variadic conversion to string. Appends each element in turn.
759 * If we have two or more things to append, we it will not reserve
760 * the space for them and will depend on strings exponential growth.
761 * If you just append once consider using toAppendFit which reserves
762 * the space needed (but does not have exponential as a result).
764 template <class... Ts>
765 typename std::enable_if<sizeof...(Ts) >= 3
767 typename std::remove_pointer<
768 typename detail::last_element<Ts...>::type
769 >::type>::value>::type
770 toAppend(const Ts&... vs) {
771 detail::toAppendStrImpl(vs...);
775 * Special version of the call that preallocates exaclty as much memory
776 * as need for arguments to be stored in target. This means we are
777 * not doing exponential growth when we append. If you are using it
778 * in a loop you are aiming at your foot with a big perf-destroying
780 * On the other hand if you are appending to a string once, this
781 * will probably save a few calls to malloc.
783 template <class... Ts>
784 typename std::enable_if<
786 typename std::remove_pointer<
787 typename detail::last_element<Ts...>::type
788 >::type>::value>::type
789 toAppendFit(const Ts&... vs) {
790 detail::reserveInTarget(vs...);
795 void toAppendFit(const Ts&) {}
798 * Variadic base case: do nothing.
801 typename std::enable_if<IsSomeString<Tgt>::value>::type
802 toAppend(Tgt* result) {
806 * Variadic base case: do nothing.
808 template <class Delimiter, class Tgt>
809 typename std::enable_if<IsSomeString<Tgt>::value>::type
810 toAppendDelim(const Delimiter& delim, Tgt* result) {
814 * 1 element: same as toAppend.
816 template <class Delimiter, class T, class Tgt>
817 typename std::enable_if<IsSomeString<Tgt>::value>::type
818 toAppendDelim(const Delimiter& delim, const T& v, Tgt* tgt) {
823 * Append to string with a delimiter in between elements. Check out
824 * comments for toAppend for details about memory allocation.
826 template <class Delimiter, class... Ts>
827 typename std::enable_if<sizeof...(Ts) >= 3
829 typename std::remove_pointer<
830 typename detail::last_element<Ts...>::type
831 >::type>::value>::type
832 toAppendDelim(const Delimiter& delim, const Ts&... vs) {
833 detail::toAppendDelimStrImpl(delim, vs...);
837 * Detail in comment for toAppendFit
839 template <class Delimiter, class... Ts>
840 typename std::enable_if<
842 typename std::remove_pointer<
843 typename detail::last_element<Ts...>::type
844 >::type>::value>::type
845 toAppendDelimFit(const Delimiter& delim, const Ts&... vs) {
846 detail::reserveInTargetDelim(delim, vs...);
847 toAppendDelim(delim, vs...);
850 template <class De, class Ts>
851 void toAppendDelimFit(const De&, const Ts&) {}
854 * to<SomeString>(v1, v2, ...) uses toAppend() (see below) as back-end
857 template <class Tgt, class... Ts>
858 typename std::enable_if<
859 IsSomeString<Tgt>::value && (
860 sizeof...(Ts) != 1 ||
861 !std::is_same<Tgt, typename detail::last_element<Ts...>::type>::value),
863 to(const Ts&... vs) {
865 toAppendFit(vs..., &result);
870 * toDelim<SomeString>(SomeString str) returns itself.
872 template <class Tgt, class Delim, class Src>
873 typename std::enable_if<
874 IsSomeString<Tgt>::value && std::is_same<Tgt, Src>::value,
876 toDelim(const Delim& delim, const Src & value) {
881 * toDelim<SomeString>(delim, v1, v2, ...) uses toAppendDelim() as
882 * back-end for all types.
884 template <class Tgt, class Delim, class... Ts>
885 typename std::enable_if<
886 IsSomeString<Tgt>::value && (
887 sizeof...(Ts) != 1 ||
888 !std::is_same<Tgt, typename detail::last_element<Ts...>::type>::value),
890 toDelim(const Delim& delim, const Ts&... vs) {
892 toAppendDelimFit(delim, vs..., &result);
896 /*******************************************************************************
897 * Conversions from string types to integral types.
898 ******************************************************************************/
903 * Finds the first non-digit in a string. The number of digits
904 * searched depends on the precision of the Tgt integral. Assumes the
905 * string starts with NO whitespace and NO sign.
907 * The semantics of the routine is:
909 * if (b >= e || !isdigit(*b)) return b;
912 * Complete unrolling marks bottom-line (i.e. entire conversion)
913 * improvements of 20%.
916 const char* findFirstNonDigit(const char* b, const char* e) {
918 auto const c = static_cast<unsigned>(*b) - '0';
924 // Maximum value of number when represented as a string
925 template <class T> struct MaxString {
926 static const char*const value;
931 * Lookup tables that converts from a decimal character value to an integral
932 * binary value, shifted by a decimal "shift" multiplier.
933 * For all character values in the range '0'..'9', the table at those
934 * index locations returns the actual decimal value shifted by the multiplier.
935 * For all other values, the lookup table returns an invalid OOR value.
937 // Out-of-range flag value, larger than the largest value that can fit in
938 // four decimal bytes (9999), but four of these added up together should
939 // still not overflow uint16_t.
940 constexpr int32_t OOR = 10000;
942 __attribute__((__aligned__(16))) constexpr uint16_t shift1[] = {
943 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 0-9
944 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 10
945 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 20
946 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 30
947 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, 0, // 40
948 1, 2, 3, 4, 5, 6, 7, 8, 9, OOR, OOR,
949 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 60
950 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 70
951 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 80
952 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 90
953 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 100
954 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 110
955 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 120
956 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 130
957 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 140
958 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 150
959 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 160
960 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 170
961 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 180
962 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 190
963 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 200
964 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 210
965 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 220
966 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 230
967 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 240
968 OOR, OOR, OOR, OOR, OOR, OOR // 250
971 __attribute__((__aligned__(16))) constexpr uint16_t shift10[] = {
972 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 0-9
973 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 10
974 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 20
975 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 30
976 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, 0, // 40
977 10, 20, 30, 40, 50, 60, 70, 80, 90, OOR, OOR,
978 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 60
979 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 70
980 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 80
981 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 90
982 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 100
983 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 110
984 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 120
985 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 130
986 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 140
987 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 150
988 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 160
989 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 170
990 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 180
991 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 190
992 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 200
993 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 210
994 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 220
995 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 230
996 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 240
997 OOR, OOR, OOR, OOR, OOR, OOR // 250
1000 __attribute__((__aligned__(16))) constexpr uint16_t shift100[] = {
1001 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 0-9
1002 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 10
1003 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 20
1004 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 30
1005 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, 0, // 40
1006 100, 200, 300, 400, 500, 600, 700, 800, 900, OOR, OOR,
1007 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 60
1008 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 70
1009 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 80
1010 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 90
1011 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 100
1012 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 110
1013 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 120
1014 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 130
1015 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 140
1016 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 150
1017 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 160
1018 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 170
1019 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 180
1020 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 190
1021 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 200
1022 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 210
1023 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 220
1024 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 230
1025 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 240
1026 OOR, OOR, OOR, OOR, OOR, OOR // 250
1029 __attribute__((__aligned__(16))) constexpr uint16_t shift1000[] = {
1030 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 0-9
1031 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 10
1032 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 20
1033 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 30
1034 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, 0, // 40
1035 1000, 2000, 3000, 4000, 5000, 6000, 7000, 8000, 9000, OOR, OOR,
1036 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 60
1037 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 70
1038 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 80
1039 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 90
1040 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 100
1041 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 110
1042 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 120
1043 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 130
1044 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 140
1045 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 150
1046 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 160
1047 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 170
1048 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 180
1049 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 190
1050 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 200
1051 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 210
1052 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 220
1053 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 230
1054 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 240
1055 OOR, OOR, OOR, OOR, OOR, OOR // 250
1059 * String represented as a pair of pointers to char to unsigned
1060 * integrals. Assumes NO whitespace before or after, and also that the
1061 * string is composed entirely of digits. Tgt must be unsigned, and no
1062 * sign is allowed in the string (even it's '+'). String may be empty,
1063 * in which case digits_to throws.
1065 template <class Tgt>
1066 Tgt digits_to(const char * b, const char * e) {
1068 static_assert(!std::is_signed<Tgt>::value, "Unsigned type expected");
1071 const size_t size = e - b;
1073 /* Although the string is entirely made of digits, we still need to
1074 * check for overflow.
1076 if (size >= std::numeric_limits<Tgt>::digits10 + 1) {
1077 // Leading zeros? If so, recurse to keep things simple
1078 if (b < e && *b == '0') {
1080 if (b == e) return 0; // just zeros, e.g. "0000"
1081 if (*b != '0') return digits_to<Tgt>(b, e);
1084 FOLLY_RANGE_CHECK_BEGIN_END(
1085 size == std::numeric_limits<Tgt>::digits10 + 1 &&
1086 strncmp(b, detail::MaxString<Tgt>::value, size) <= 0,
1087 "Numeric overflow upon conversion", b, e);
1090 // Here we know that the number won't overflow when
1091 // converted. Proceed without checks.
1095 for (; e - b >= 4; b += 4) {
1097 const int32_t r0 = shift1000[static_cast<size_t>(b[0])];
1098 const int32_t r1 = shift100[static_cast<size_t>(b[1])];
1099 const int32_t r2 = shift10[static_cast<size_t>(b[2])];
1100 const int32_t r3 = shift1[static_cast<size_t>(b[3])];
1101 const auto sum = r0 + r1 + r2 + r3;
1102 assert(sum < OOR && "Assumption: string only has digits");
1108 const int32_t r0 = shift100[static_cast<size_t>(b[0])];
1109 const int32_t r1 = shift10[static_cast<size_t>(b[1])];
1110 const int32_t r2 = shift1[static_cast<size_t>(b[2])];
1111 const auto sum = r0 + r1 + r2;
1112 assert(sum < OOR && "Assumption: string only has digits");
1113 return result * 1000 + sum;
1116 const int32_t r0 = shift10[static_cast<size_t>(b[0])];
1117 const int32_t r1 = shift1[static_cast<size_t>(b[1])];
1118 const auto sum = r0 + r1;
1119 assert(sum < OOR && "Assumption: string only has digits");
1120 return result * 100 + sum;
1123 const int32_t sum = shift1[static_cast<size_t>(b[0])];
1124 assert(sum < OOR && "Assumption: string only has digits");
1125 return result * 10 + sum;
1130 FOLLY_RANGE_CHECK_BEGIN_END(size > 0,
1131 "Found no digits to convert in input", b, e);
1136 bool str_to_bool(StringPiece * src);
1138 } // namespace detail
1141 * String represented as a pair of pointers to char to unsigned
1142 * integrals. Assumes NO whitespace before or after.
1144 template <class Tgt>
1145 typename std::enable_if<
1146 std::is_integral<Tgt>::value && !std::is_signed<Tgt>::value
1147 && !std::is_same<typename std::remove_cv<Tgt>::type, bool>::value,
1149 to(const char * b, const char * e) {
1150 return detail::digits_to<Tgt>(b, e);
1154 * String represented as a pair of pointers to char to signed
1155 * integrals. Assumes NO whitespace before or after. Allows an
1156 * optional leading sign.
1158 template <class Tgt>
1159 typename std::enable_if<
1160 std::is_integral<Tgt>::value && std::is_signed<Tgt>::value,
1162 to(const char * b, const char * e) {
1163 FOLLY_RANGE_CHECK(b < e, "Empty input string in conversion to integral",
1164 to<std::string>("b: ", intptr_t(b), " e: ", intptr_t(e)));
1167 Tgt result = -to<typename std::make_unsigned<Tgt>::type>(b + 1, e);
1168 FOLLY_RANGE_CHECK_BEGIN_END(result <= 0, "Negative overflow.", b, e);
1171 FOLLY_RANGE_CHECK_BEGIN_END(*b == '+', "Invalid lead character", b, e);
1174 Tgt result = to<typename std::make_unsigned<Tgt>::type>(b, e);
1175 FOLLY_RANGE_CHECK_BEGIN_END(result >= 0, "Overflow", b, e);
1180 * Parsing strings to integrals. These routines differ from
1181 * to<integral>(string) in that they take a POINTER TO a StringPiece
1182 * and alter that StringPiece to reflect progress information.
1186 * StringPiece to integrals, with progress information. Alters the
1187 * StringPiece parameter to munch the already-parsed characters.
1189 template <class Tgt>
1190 typename std::enable_if<
1191 std::is_integral<Tgt>::value
1192 && !std::is_same<typename std::remove_cv<Tgt>::type, bool>::value,
1194 to(StringPiece * src) {
1196 auto b = src->data(), past = src->data() + src->size();
1198 FOLLY_RANGE_CHECK_STRINGPIECE(b < past,
1199 "No digits found in input string", *src);
1200 if (!isspace(*b)) break;
1205 // First digit is customized because we test for sign
1206 bool negative = false;
1207 /* static */ if (std::is_signed<Tgt>::value) {
1212 FOLLY_RANGE_CHECK_STRINGPIECE(*m == '+', "Invalid leading character in "
1213 "conversion to integral", *src);
1219 FOLLY_RANGE_CHECK_STRINGPIECE(m < past, "No digits found in input string",
1221 FOLLY_RANGE_CHECK_STRINGPIECE(isdigit(*m), "Non-digit character found", *src);
1222 m = detail::findFirstNonDigit<Tgt>(m + 1, past);
1225 /* static */ if (!std::is_signed<Tgt>::value) {
1226 result = detail::digits_to<typename std::make_unsigned<Tgt>::type>(b, m);
1228 auto t = detail::digits_to<typename std::make_unsigned<Tgt>::type>(b, m);
1231 FOLLY_RANGE_CHECK_STRINGPIECE(is_non_positive(result),
1232 "Negative overflow", *src);
1235 FOLLY_RANGE_CHECK_STRINGPIECE(is_non_negative(result), "Overflow", *src);
1238 src->advance(m - src->data());
1243 * StringPiece to bool, with progress information. Alters the
1244 * StringPiece parameter to munch the already-parsed characters.
1246 template <class Tgt>
1247 typename std::enable_if<
1248 std::is_same<typename std::remove_cv<Tgt>::type, bool>::value,
1250 to(StringPiece * src) {
1251 return detail::str_to_bool(src);
1257 * Enforce that the suffix following a number is made up only of whitespace.
1259 inline void enforceWhitespace(const char* b, const char* e) {
1260 for (; b != e; ++b) {
1261 FOLLY_RANGE_CHECK_BEGIN_END(isspace(*b),
1262 to<std::string>("Non-whitespace: ", *b),
1267 } // namespace detail
1270 * String or StringPiece to integrals. Accepts leading and trailing
1271 * whitespace, but no non-space trailing characters.
1273 template <class Tgt>
1274 typename std::enable_if<
1275 std::is_integral<Tgt>::value,
1277 to(StringPiece src) {
1278 Tgt result = to<Tgt>(&src);
1279 detail::enforceWhitespace(src.data(), src.data() + src.size());
1283 /*******************************************************************************
1284 * Conversions from string types to floating-point types.
1285 ******************************************************************************/
1288 * StringPiece to double, with progress information. Alters the
1289 * StringPiece parameter to munch the already-parsed characters.
1291 template <class Tgt>
1292 inline typename std::enable_if<
1293 std::is_floating_point<Tgt>::value,
1295 to(StringPiece *const src) {
1296 using namespace double_conversion;
1297 static StringToDoubleConverter
1298 conv(StringToDoubleConverter::ALLOW_TRAILING_JUNK
1299 | StringToDoubleConverter::ALLOW_LEADING_SPACES,
1301 // return this for junk input string
1302 std::numeric_limits<double>::quiet_NaN(),
1305 FOLLY_RANGE_CHECK_STRINGPIECE(!src->empty(),
1306 "No digits found in input string", *src);
1309 auto result = conv.StringToDouble(src->data(),
1310 static_cast<int>(src->size()),
1311 &length); // processed char count
1313 if (!std::isnan(result)) {
1314 src->advance(length);
1318 for (;; src->advance(1)) {
1320 throw std::range_error("Unable to convert an empty string"
1321 " to a floating point value.");
1323 if (!isspace(src->front())) {
1328 // Was that "inf[inity]"?
1329 if (src->size() >= 3 && toupper((*src)[0]) == 'I'
1330 && toupper((*src)[1]) == 'N' && toupper((*src)[2]) == 'F') {
1331 if (src->size() >= 8 &&
1332 toupper((*src)[3]) == 'I' &&
1333 toupper((*src)[4]) == 'N' &&
1334 toupper((*src)[5]) == 'I' &&
1335 toupper((*src)[6]) == 'T' &&
1336 toupper((*src)[7]) == 'Y') {
1341 return std::numeric_limits<Tgt>::infinity();
1344 // Was that "-inf[inity]"?
1345 if (src->size() >= 4 && toupper((*src)[0]) == '-'
1346 && toupper((*src)[1]) == 'I' && toupper((*src)[2]) == 'N'
1347 && toupper((*src)[3]) == 'F') {
1348 if (src->size() >= 9 &&
1349 toupper((*src)[4]) == 'I' &&
1350 toupper((*src)[5]) == 'N' &&
1351 toupper((*src)[6]) == 'I' &&
1352 toupper((*src)[7]) == 'T' &&
1353 toupper((*src)[8]) == 'Y') {
1358 return -std::numeric_limits<Tgt>::infinity();
1362 if (src->size() >= 3 && toupper((*src)[0]) == 'N'
1363 && toupper((*src)[1]) == 'A' && toupper((*src)[2]) == 'N') {
1365 return std::numeric_limits<Tgt>::quiet_NaN();
1369 if (src->size() >= 4 &&
1370 toupper((*src)[0]) == '-' &&
1371 toupper((*src)[1]) == 'N' &&
1372 toupper((*src)[2]) == 'A' &&
1373 toupper((*src)[3]) == 'N') {
1375 return -std::numeric_limits<Tgt>::quiet_NaN();
1379 throw std::range_error("Unable to convert \"" + src->toString()
1380 + "\" to a floating point value.");
1384 * Any string, const char*, or StringPiece to double.
1386 template <class Tgt>
1387 typename std::enable_if<
1388 std::is_floating_point<Tgt>::value,
1390 to(StringPiece src) {
1391 Tgt result = to<double>(&src);
1392 detail::enforceWhitespace(src.data(), src.data() + src.size());
1396 /*******************************************************************************
1397 * Integral to floating point and back
1398 ******************************************************************************/
1401 * Checked conversion from integral to flating point and back. The
1402 * result must be convertible back to the source type without loss of
1403 * precision. This seems Draconian but sometimes is what's needed, and
1404 * complements existing routines nicely. For various rounding
1405 * routines, see <math>.
1407 template <class Tgt, class Src>
1408 typename std::enable_if<
1409 (std::is_integral<Src>::value && std::is_floating_point<Tgt>::value)
1411 (std::is_floating_point<Src>::value && std::is_integral<Tgt>::value),
1413 to(const Src & value) {
1415 auto witness = static_cast<Src>(result);
1416 if (value != witness) {
1417 throw std::range_error(
1418 to<std::string>("to<>: loss of precision when converting ", value,
1419 " to type ", typeid(Tgt).name()).c_str());
1424 /*******************************************************************************
1425 * Enum to anything and back
1426 ******************************************************************************/
1428 #if defined(__clang__) || __GNUC_PREREQ(4, 7)
1429 // std::underlying_type became available by gcc 4.7.0
1431 template <class Tgt, class Src>
1432 typename std::enable_if<
1433 std::is_enum<Src>::value && !std::is_same<Src, Tgt>::value, Tgt>::type
1434 to(const Src & value) {
1435 return to<Tgt>(static_cast<typename std::underlying_type<Src>::type>(value));
1438 template <class Tgt, class Src>
1439 typename std::enable_if<
1440 std::is_enum<Tgt>::value && !std::is_same<Src, Tgt>::value, Tgt>::type
1441 to(const Src & value) {
1442 return static_cast<Tgt>(to<typename std::underlying_type<Tgt>::type>(value));
1447 template <class Tgt, class Src>
1448 typename std::enable_if<
1449 std::is_enum<Src>::value && !std::is_same<Src, Tgt>::value, Tgt>::type
1450 to(const Src & value) {
1451 /* static */ if (Src(-1) < 0) {
1452 /* static */ if (sizeof(Src) <= sizeof(int)) {
1453 return to<Tgt>(static_cast<int>(value));
1455 return to<Tgt>(static_cast<long>(value));
1458 /* static */ if (sizeof(Src) <= sizeof(int)) {
1459 return to<Tgt>(static_cast<unsigned int>(value));
1461 return to<Tgt>(static_cast<unsigned long>(value));
1466 template <class Tgt, class Src>
1467 typename std::enable_if<
1468 std::is_enum<Tgt>::value && !std::is_same<Src, Tgt>::value, Tgt>::type
1469 to(const Src & value) {
1470 /* static */ if (Tgt(-1) < 0) {
1471 /* static */ if (sizeof(Tgt) <= sizeof(int)) {
1472 return static_cast<Tgt>(to<int>(value));
1474 return static_cast<Tgt>(to<long>(value));
1477 /* static */ if (sizeof(Tgt) <= sizeof(int)) {
1478 return static_cast<Tgt>(to<unsigned int>(value));
1480 return static_cast<Tgt>(to<unsigned long>(value));
1485 #endif // gcc 4.7 onwards
1487 } // namespace folly
1489 // FOLLY_CONV_INTERNAL is defined by Conv.cpp. Keep the FOLLY_RANGE_CHECK
1490 // macro for use in Conv.cpp, but #undefine it everywhere else we are included,
1491 // to avoid defining this global macro name in other files that include Conv.h.
1492 #ifndef FOLLY_CONV_INTERNAL
1493 #undef FOLLY_RANGE_CHECK
1494 #undef FOLLY_RANGE_CHECK_BEGIN_END
1495 #undef FOLLY_RANGE_CHECK_STRINGPIECE
1496 #undef FOLLY_RANGE_CHECK_STRINGIZE
1497 #undef FOLLY_RANGE_CHECK_STRINGIZE2
1500 #endif /* FOLLY_BASE_CONV_H_ */