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) \
50 ((condition) ? (void)0 : throw std::range_error( \
51 (std::string(__FILE__ "(" FOLLY_RANGE_CHECK_STRINGIZE2(__LINE__) "): ") \
52 + (message)).c_str()))
57 * The identity conversion function.
58 * to<T>(T) returns itself for all types T.
60 template <class Tgt, class Src>
61 typename std::enable_if<std::is_same<Tgt, Src>::value, Tgt>::type
62 to(const Src & value) {
66 template <class Tgt, class Src>
67 typename std::enable_if<std::is_same<Tgt, Src>::value, Tgt>::type
69 return std::move(value);
72 /*******************************************************************************
73 * Integral to integral
74 ******************************************************************************/
77 * Checked conversion from integral to integral. The checks are only
78 * performed when meaningful, e.g. conversion from int to long goes
81 template <class Tgt, class Src>
82 typename std::enable_if<
83 std::is_integral<Src>::value
84 && std::is_integral<Tgt>::value
85 && !std::is_same<Tgt, Src>::value,
87 to(const Src & value) {
88 /* static */ if (std::numeric_limits<Tgt>::max()
89 < std::numeric_limits<Src>::max()) {
91 (!greater_than<Tgt, std::numeric_limits<Tgt>::max()>(value)),
95 /* static */ if (std::is_signed<Src>::value &&
96 (!std::is_signed<Tgt>::value || sizeof(Src) > sizeof(Tgt))) {
98 (!less_than<Tgt, std::numeric_limits<Tgt>::min()>(value)),
102 return static_cast<Tgt>(value);
105 /*******************************************************************************
106 * Floating point to floating point
107 ******************************************************************************/
109 template <class Tgt, class Src>
110 typename std::enable_if<
111 std::is_floating_point<Tgt>::value
112 && std::is_floating_point<Src>::value
113 && !std::is_same<Tgt, Src>::value,
115 to(const Src & value) {
116 /* static */ if (std::numeric_limits<Tgt>::max() <
117 std::numeric_limits<Src>::max()) {
118 FOLLY_RANGE_CHECK(value <= std::numeric_limits<Tgt>::max(),
120 FOLLY_RANGE_CHECK(value >= -std::numeric_limits<Tgt>::max(),
121 "Negative overflow");
123 return boost::implicit_cast<Tgt>(value);
126 /*******************************************************************************
128 ******************************************************************************/
133 const T& getLastElement(const T & v) {
137 template <class T, class... Ts>
138 typename std::tuple_element<
140 std::tuple<T, Ts...> >::type const&
141 getLastElement(const T& v, const Ts&... vs) {
142 return getLastElement(vs...);
145 // This class exists to specialize away std::tuple_element in the case where we
146 // have 0 template arguments. Without this, Clang/libc++ will blow a
147 // static_assert even if tuple_element is protected by an enable_if.
148 template <class... Ts>
149 struct last_element {
150 typedef typename std::enable_if<
152 typename std::tuple_element<
153 sizeof...(Ts) - 1, std::tuple<Ts...>
158 struct last_element<> {
162 } // namespace detail
164 /*******************************************************************************
165 * Conversions from integral types to string types.
166 ******************************************************************************/
168 #if FOLLY_HAVE_INT128_T
171 template <typename IntegerType>
172 constexpr unsigned int
174 return ceil((double(sizeof(IntegerType) * CHAR_BIT) * M_LN2) / M_LN10);
178 unsafeTelescope128(char * buffer, size_t room, unsigned __int128 x) {
179 typedef unsigned __int128 Usrc;
182 while (x >= (Usrc(1) << 64)) { // Using 128-bit division while needed
183 const auto y = x / 10;
184 const auto digit = x % 10;
186 buffer[p--] = '0' + digit;
190 uint64_t xx = x; // Moving to faster 64-bit division thereafter
193 const auto y = xx / 10ULL;
194 const auto digit = xx % 10ULL;
196 buffer[p--] = '0' + digit;
200 buffer[p] = '0' + xx;
209 * Returns the number of digits in the base 10 representation of an
210 * uint64_t. Useful for preallocating buffers and such. It's also used
211 * internally, see below. Measurements suggest that defining a
212 * separate overload for 32-bit integers is not worthwhile.
215 inline uint32_t digits10(uint64_t v) {
218 if (LIKELY(v < 10)) return result;
219 if (LIKELY(v < 100)) return result + 1;
220 if (LIKELY(v < 1000)) return result + 2;
221 if (LIKELY(v < 10000)) return result + 3;
222 // Skip ahead by 4 orders of magnitude
229 * Copies the ASCII base 10 representation of v into buffer and
230 * returns the number of bytes written. Does NOT append a \0. Assumes
231 * the buffer points to digits10(v) bytes of valid memory. Note that
232 * uint64 needs at most 20 bytes, uint32_t needs at most 10 bytes,
233 * uint16_t needs at most 5 bytes, and so on. Measurements suggest
234 * that defining a separate overload for 32-bit integers is not
237 * This primitive is unsafe because it makes the size assumption and
238 * because it does not add a terminating \0.
241 inline uint32_t uint64ToBufferUnsafe(uint64_t v, char *const buffer) {
242 auto const result = digits10(v);
243 // WARNING: using size_t or pointer arithmetic for pos slows down
244 // the loop below 20x. This is because several 32-bit ops can be
245 // done in parallel, but only fewer 64-bit ones.
246 uint32_t pos = result - 1;
248 // Keep these together so a peephole optimization "sees" them and
249 // computes them in one shot.
250 auto const q = v / 10;
251 auto const r = static_cast<uint32_t>(v % 10);
252 buffer[pos--] = '0' + r;
255 // Last digit is trivial to handle
256 buffer[pos] = static_cast<uint32_t>(v) + '0';
261 * A single char gets appended.
264 void toAppend(char value, Tgt * result) {
269 constexpr typename std::enable_if<
270 std::is_same<T, char>::value,
272 estimateSpaceNeeded(T) {
277 * Ubiquitous helper template for writing string appenders
279 template <class T> struct IsSomeString {
280 enum { value = std::is_same<T, std::string>::value
281 || std::is_same<T, fbstring>::value };
285 * Everything implicitly convertible to const char* gets appended.
287 template <class Tgt, class Src>
288 typename std::enable_if<
289 std::is_convertible<Src, const char*>::value
290 && IsSomeString<Tgt>::value>::type
291 toAppend(Src value, Tgt * result) {
292 // Treat null pointers like an empty string, as in:
293 // operator<<(std::ostream&, const char*).
294 const char* c = value;
296 result->append(value);
301 typename std::enable_if<
302 std::is_convertible<Src, const char*>::value,
304 estimateSpaceNeeded(Src value) {
305 const char *c = value;
307 return folly::StringPiece(value).size();
313 typename std::enable_if<
314 (std::is_convertible<Src, folly::StringPiece>::value ||
315 IsSomeString<Src>::value) &&
316 !std::is_convertible<Src, const char*>::value,
318 estimateSpaceNeeded(Src value) {
319 return folly::StringPiece(value).size();
323 typename std::enable_if<
324 std::is_pointer<Src>::value &&
325 IsSomeString<std::remove_pointer<Src>>::value,
327 estimateSpaceNeeded(Src value) {
328 return value->size();
332 * Strings get appended, too.
334 template <class Tgt, class Src>
335 typename std::enable_if<
336 IsSomeString<Src>::value && IsSomeString<Tgt>::value>::type
337 toAppend(const Src& value, Tgt * result) {
338 result->append(value);
342 * and StringPiece objects too
345 typename std::enable_if<
346 IsSomeString<Tgt>::value>::type
347 toAppend(StringPiece value, Tgt * result) {
348 result->append(value.data(), value.size());
352 * There's no implicit conversion from fbstring to other string types,
353 * so make a specialization.
356 typename std::enable_if<
357 IsSomeString<Tgt>::value>::type
358 toAppend(const fbstring& value, Tgt * result) {
359 result->append(value.data(), value.size());
362 #if FOLLY_HAVE_INT128_T
364 * Special handling for 128 bit integers.
369 toAppend(__int128 value, Tgt * result) {
370 typedef unsigned __int128 Usrc;
371 char buffer[detail::digitsEnough<unsigned __int128>() + 1];
375 p = detail::unsafeTelescope128(buffer, sizeof(buffer), Usrc(-value));
378 p = detail::unsafeTelescope128(buffer, sizeof(buffer), value);
381 result->append(buffer + p, buffer + sizeof(buffer));
386 toAppend(unsigned __int128 value, Tgt * result) {
387 char buffer[detail::digitsEnough<unsigned __int128>()];
390 p = detail::unsafeTelescope128(buffer, sizeof(buffer), value);
392 result->append(buffer + p, buffer + sizeof(buffer));
396 constexpr typename std::enable_if<
397 std::is_same<T, __int128>::value,
399 estimateSpaceNeeded(T) {
400 return detail::digitsEnough<__int128>();
404 constexpr typename std::enable_if<
405 std::is_same<T, unsigned __int128>::value,
407 estimateSpaceNeeded(T) {
408 return detail::digitsEnough<unsigned __int128>();
414 * int32_t and int64_t to string (by appending) go through here. The
415 * result is APPENDED to a preexisting string passed as the second
416 * parameter. This should be efficient with fbstring because fbstring
417 * incurs no dynamic allocation below 23 bytes and no number has more
418 * than 22 bytes in its textual representation (20 for digits, one for
419 * sign, one for the terminating 0).
421 template <class Tgt, class Src>
422 typename std::enable_if<
423 std::is_integral<Src>::value && std::is_signed<Src>::value &&
424 IsSomeString<Tgt>::value && sizeof(Src) >= 4>::type
425 toAppend(Src value, Tgt * result) {
428 result->push_back('-');
429 result->append(buffer, uint64ToBufferUnsafe(-uint64_t(value), buffer));
431 result->append(buffer, uint64ToBufferUnsafe(value, buffer));
436 typename std::enable_if<
437 std::is_integral<Src>::value && std::is_signed<Src>::value
438 && sizeof(Src) >= 4 && sizeof(Src) < 16,
440 estimateSpaceNeeded(Src value) {
442 return 1 + digits10(static_cast<uint64_t>(-value));
445 return digits10(static_cast<uint64_t>(value));
449 * As above, but for uint32_t and uint64_t.
451 template <class Tgt, class Src>
452 typename std::enable_if<
453 std::is_integral<Src>::value && !std::is_signed<Src>::value
454 && IsSomeString<Tgt>::value && sizeof(Src) >= 4>::type
455 toAppend(Src value, Tgt * result) {
457 result->append(buffer, buffer + uint64ToBufferUnsafe(value, buffer));
461 typename std::enable_if<
462 std::is_integral<Src>::value && !std::is_signed<Src>::value
463 && sizeof(Src) >= 4 && sizeof(Src) < 16,
465 estimateSpaceNeeded(Src value) {
466 return digits10(value);
470 * All small signed and unsigned integers to string go through 32-bit
471 * types int32_t and uint32_t, respectively.
473 template <class Tgt, class Src>
474 typename std::enable_if<
475 std::is_integral<Src>::value
476 && IsSomeString<Tgt>::value && sizeof(Src) < 4>::type
477 toAppend(Src value, Tgt * result) {
479 std::conditional<std::is_signed<Src>::value, int64_t, uint64_t>::type
481 toAppend<Tgt>(static_cast<Intermediate>(value), result);
485 typename std::enable_if<
486 std::is_integral<Src>::value
488 && !std::is_same<Src, char>::value,
490 estimateSpaceNeeded(Src value) {
492 std::conditional<std::is_signed<Src>::value, int64_t, uint64_t>::type
494 return estimateSpaceNeeded(static_cast<Intermediate>(value));
497 #if defined(__clang__) || __GNUC_PREREQ(4, 7)
498 // std::underlying_type became available by gcc 4.7.0
501 * Enumerated values get appended as integers.
503 template <class Tgt, class Src>
504 typename std::enable_if<
505 std::is_enum<Src>::value && IsSomeString<Tgt>::value>::type
506 toAppend(Src value, Tgt * result) {
508 static_cast<typename std::underlying_type<Src>::type>(value), result);
512 typename std::enable_if<
513 std::is_enum<Src>::value, size_t>::type
514 estimateSpaceNeeded(Src value) {
515 return estimateSpaceNeeded(
516 static_cast<typename std::underlying_type<Src>::type>(value));
522 * Enumerated values get appended as integers.
524 template <class Tgt, class Src>
525 typename std::enable_if<
526 std::is_enum<Src>::value && IsSomeString<Tgt>::value>::type
527 toAppend(Src value, Tgt * result) {
528 /* static */ if (Src(-1) < 0) {
529 /* static */ if (sizeof(Src) <= sizeof(int)) {
530 toAppend(static_cast<int>(value), result);
532 toAppend(static_cast<long>(value), result);
535 /* static */ if (sizeof(Src) <= sizeof(int)) {
536 toAppend(static_cast<unsigned int>(value), result);
538 toAppend(static_cast<unsigned long>(value), result);
544 typename std::enable_if<
545 std::is_enum<Src>::value, size_t>::type
546 estimateSpaceNeeded(Src value) {
547 /* static */ if (Src(-1) < 0) {
548 /* static */ if (sizeof(Src) <= sizeof(int)) {
549 return estimateSpaceNeeded(static_cast<int>(value));
551 return estimateSpaceNeeded(static_cast<long>(value));
554 /* static */ if (sizeof(Src) <= sizeof(int)) {
555 return estimateSpaceNeeded(static_cast<unsigned int>(value));
557 return estimateSpaceNeeded(static_cast<unsigned long>(value));
562 #endif // gcc 4.7 onwards
564 /*******************************************************************************
565 * Conversions from floating-point types to string types.
566 ******************************************************************************/
569 constexpr int kConvMaxDecimalInShortestLow = -6;
570 constexpr int kConvMaxDecimalInShortestHigh = 21;
573 /** Wrapper around DoubleToStringConverter **/
574 template <class Tgt, class Src>
575 typename std::enable_if<
576 std::is_floating_point<Src>::value
577 && IsSomeString<Tgt>::value>::type
581 double_conversion::DoubleToStringConverter::DtoaMode mode,
582 unsigned int numDigits) {
583 using namespace double_conversion;
584 DoubleToStringConverter
585 conv(DoubleToStringConverter::NO_FLAGS,
586 "infinity", "NaN", 'E',
587 detail::kConvMaxDecimalInShortestLow,
588 detail::kConvMaxDecimalInShortestHigh,
589 6, // max leading padding zeros
590 1); // max trailing padding zeros
592 StringBuilder builder(buffer, sizeof(buffer));
594 case DoubleToStringConverter::SHORTEST:
595 conv.ToShortest(value, &builder);
597 case DoubleToStringConverter::FIXED:
598 conv.ToFixed(value, numDigits, &builder);
601 CHECK(mode == DoubleToStringConverter::PRECISION);
602 conv.ToPrecision(value, numDigits, &builder);
605 const size_t length = builder.position();
607 result->append(buffer, length);
611 * As above, but for floating point
613 template <class Tgt, class Src>
614 typename std::enable_if<
615 std::is_floating_point<Src>::value
616 && IsSomeString<Tgt>::value>::type
617 toAppend(Src value, Tgt * result) {
619 value, result, double_conversion::DoubleToStringConverter::SHORTEST, 0);
623 * Upper bound of the length of the output from
624 * DoubleToStringConverter::ToShortest(double, StringBuilder*),
625 * as used in toAppend(double, string*).
628 typename std::enable_if<
629 std::is_floating_point<Src>::value, size_t>::type
630 estimateSpaceNeeded(Src value) {
631 // kBase10MaximalLength is 17. We add 1 for decimal point,
632 // e.g. 10.0/9 is 17 digits and 18 characters, including the decimal point.
633 constexpr int kMaxMantissaSpace =
634 double_conversion::DoubleToStringConverter::kBase10MaximalLength + 1;
635 // strlen("E-") + digits10(numeric_limits<double>::max_exponent10)
636 constexpr int kMaxExponentSpace = 2 + 3;
637 static const int kMaxPositiveSpace = std::max({
638 // E.g. 1.1111111111111111E-100.
639 kMaxMantissaSpace + kMaxExponentSpace,
640 // E.g. 0.000001.1111111111111111, if kConvMaxDecimalInShortestLow is -6.
641 kMaxMantissaSpace - detail::kConvMaxDecimalInShortestLow,
642 // If kConvMaxDecimalInShortestHigh is 21, then 1e21 is the smallest
643 // number > 1 which ToShortest outputs in exponential notation,
644 // so 21 is the longest non-exponential number > 1.
645 detail::kConvMaxDecimalInShortestHigh
647 return kMaxPositiveSpace + (value < 0); // +1 for minus sign, if negative
651 * This can be specialized, together with adding specialization
652 * for estimateSpaceNeed for your type, so that we allocate
653 * as much as you need instead of the default
656 struct HasLengthEstimator : std::false_type {};
659 constexpr typename std::enable_if<
660 !std::is_fundamental<Src>::value
661 #ifdef FOLLY_HAVE_INT128_T
662 // On OSX 10.10, is_fundamental<__int128> is false :-O
663 && !std::is_same<__int128, Src>::value
664 && !std::is_same<unsigned __int128, Src>::value
666 && !IsSomeString<Src>::value
667 && !std::is_convertible<Src, const char*>::value
668 && !std::is_convertible<Src, StringPiece>::value
669 && !std::is_enum<Src>::value
670 && !HasLengthEstimator<Src>::value,
672 estimateSpaceNeeded(const Src&) {
673 return sizeof(Src) + 1; // dumbest best effort ever?
678 inline size_t estimateSpaceToReserve(size_t sofar) {
682 template <class T, class... Ts>
683 size_t estimateSpaceToReserve(size_t sofar, const T& v, const Ts&... vs) {
684 return estimateSpaceToReserve(sofar + estimateSpaceNeeded(v), vs...);
688 size_t estimateSpaceToReserve(size_t sofar, const T& v) {
689 return sofar + estimateSpaceNeeded(v);
693 void reserveInTarget(const Ts&...vs) {
694 getLastElement(vs...)->reserve(estimateSpaceToReserve(0, vs...));
697 template<class Delimiter, class...Ts>
698 void reserveInTargetDelim(const Delimiter& d, const Ts&...vs) {
699 static_assert(sizeof...(vs) >= 2, "Needs at least 2 args");
700 size_t fordelim = (sizeof...(vs) - 2) * estimateSpaceToReserve(0, d);
701 getLastElement(vs...)->reserve(estimateSpaceToReserve(fordelim, vs...));
705 * Variadic base case: append one element
707 template <class T, class Tgt>
708 typename std::enable_if<
709 IsSomeString<typename std::remove_pointer<Tgt>::type>
711 toAppendStrImpl(const T& v, Tgt result) {
715 template <class T, class... Ts>
716 typename std::enable_if<sizeof...(Ts) >= 2
718 typename std::remove_pointer<
719 typename detail::last_element<Ts...>::type
720 >::type>::value>::type
721 toAppendStrImpl(const T& v, const Ts&... vs) {
722 toAppend(v, getLastElement(vs...));
723 toAppendStrImpl(vs...);
726 template <class Delimiter, class T, class Tgt>
727 typename std::enable_if<
728 IsSomeString<typename std::remove_pointer<Tgt>::type>
730 toAppendDelimStrImpl(const Delimiter& delim, const T& v, Tgt result) {
734 template <class Delimiter, class T, class... Ts>
735 typename std::enable_if<sizeof...(Ts) >= 2
737 typename std::remove_pointer<
738 typename detail::last_element<Ts...>::type
739 >::type>::value>::type
740 toAppendDelimStrImpl(const Delimiter& delim, const T& v, const Ts&... vs) {
741 // we are really careful here, calling toAppend with just one element does
742 // not try to estimate space needed (as we already did that). If we call
743 // toAppend(v, delim, ....) we would do unnecesary size calculation
744 toAppend(v, detail::getLastElement(vs...));
745 toAppend(delim, detail::getLastElement(vs...));
746 toAppendDelimStrImpl(delim, vs...);
752 * Variadic conversion to string. Appends each element in turn.
753 * If we have two or more things to append, we it will not reserve
754 * the space for them and will depend on strings exponential growth.
755 * If you just append once consider using toAppendFit which reserves
756 * the space needed (but does not have exponential as a result).
758 template <class... Ts>
759 typename std::enable_if<sizeof...(Ts) >= 3
761 typename std::remove_pointer<
762 typename detail::last_element<Ts...>::type
763 >::type>::value>::type
764 toAppend(const Ts&... vs) {
765 detail::toAppendStrImpl(vs...);
769 * Special version of the call that preallocates exaclty as much memory
770 * as need for arguments to be stored in target. This means we are
771 * not doing exponential growth when we append. If you are using it
772 * in a loop you are aiming at your foot with a big perf-destroying
774 * On the other hand if you are appending to a string once, this
775 * will probably save a few calls to malloc.
777 template <class... Ts>
778 typename std::enable_if<
780 typename std::remove_pointer<
781 typename detail::last_element<Ts...>::type
782 >::type>::value>::type
783 toAppendFit(const Ts&... vs) {
784 detail::reserveInTarget(vs...);
789 void toAppendFit(const Ts&) {}
792 * Variadic base case: do nothing.
795 typename std::enable_if<IsSomeString<Tgt>::value>::type
796 toAppend(Tgt* result) {
800 * Variadic base case: do nothing.
802 template <class Delimiter, class Tgt>
803 typename std::enable_if<IsSomeString<Tgt>::value>::type
804 toAppendDelim(const Delimiter& delim, Tgt* result) {
808 * 1 element: same as toAppend.
810 template <class Delimiter, class T, class Tgt>
811 typename std::enable_if<IsSomeString<Tgt>::value>::type
812 toAppendDelim(const Delimiter& delim, const T& v, Tgt* tgt) {
817 * Append to string with a delimiter in between elements. Check out
818 * comments for toAppend for details about memory allocation.
820 template <class Delimiter, class... Ts>
821 typename std::enable_if<sizeof...(Ts) >= 3
823 typename std::remove_pointer<
824 typename detail::last_element<Ts...>::type
825 >::type>::value>::type
826 toAppendDelim(const Delimiter& delim, const Ts&... vs) {
827 detail::toAppendDelimStrImpl(delim, vs...);
831 * Detail in comment for toAppendFit
833 template <class Delimiter, class... Ts>
834 typename std::enable_if<
836 typename std::remove_pointer<
837 typename detail::last_element<Ts...>::type
838 >::type>::value>::type
839 toAppendDelimFit(const Delimiter& delim, const Ts&... vs) {
840 detail::reserveInTargetDelim(delim, vs...);
841 toAppendDelim(delim, vs...);
844 template <class De, class Ts>
845 void toAppendDelimFit(const De&, const Ts&) {}
848 * to<SomeString>(v1, v2, ...) uses toAppend() (see below) as back-end
851 template <class Tgt, class... Ts>
852 typename std::enable_if<
853 IsSomeString<Tgt>::value && (
854 sizeof...(Ts) != 1 ||
855 !std::is_same<Tgt, typename detail::last_element<Ts...>::type>::value),
857 to(const Ts&... vs) {
859 toAppendFit(vs..., &result);
864 * toDelim<SomeString>(SomeString str) returns itself.
866 template <class Tgt, class Delim, class Src>
867 typename std::enable_if<
868 IsSomeString<Tgt>::value && std::is_same<Tgt, Src>::value,
870 toDelim(const Delim& delim, const Src & value) {
875 * toDelim<SomeString>(delim, v1, v2, ...) uses toAppendDelim() as
876 * back-end for all types.
878 template <class Tgt, class Delim, class... Ts>
879 typename std::enable_if<
880 IsSomeString<Tgt>::value && (
881 sizeof...(Ts) != 1 ||
882 !std::is_same<Tgt, typename detail::last_element<Ts...>::type>::value),
884 toDelim(const Delim& delim, const Ts&... vs) {
886 toAppendDelimFit(delim, vs..., &result);
890 /*******************************************************************************
891 * Conversions from string types to integral types.
892 ******************************************************************************/
897 * Finds the first non-digit in a string. The number of digits
898 * searched depends on the precision of the Tgt integral. Assumes the
899 * string starts with NO whitespace and NO sign.
901 * The semantics of the routine is:
903 * if (b >= e || !isdigit(*b)) return b;
906 * Complete unrolling marks bottom-line (i.e. entire conversion)
907 * improvements of 20%.
910 const char* findFirstNonDigit(const char* b, const char* e) {
912 auto const c = static_cast<unsigned>(*b) - '0';
918 // Maximum value of number when represented as a string
919 template <class T> struct MaxString {
920 static const char*const value;
925 * Lookup tables that converts from a decimal character value to an integral
926 * binary value, shifted by a decimal "shift" multiplier.
927 * For all character values in the range '0'..'9', the table at those
928 * index locations returns the actual decimal value shifted by the multiplier.
929 * For all other values, the lookup table returns an invalid OOR value.
931 // Out-of-range flag value, larger than the largest value that can fit in
932 // four decimal bytes (9999), but four of these added up together should
933 // still not overflow uint16_t.
934 constexpr int32_t OOR = 10000;
936 __attribute__((__aligned__(16))) constexpr uint16_t shift1[] = {
937 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 0-9
938 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 10
939 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 20
940 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 30
941 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, 0, // 40
942 1, 2, 3, 4, 5, 6, 7, 8, 9, OOR, OOR,
943 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 60
944 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 70
945 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 80
946 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 90
947 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 100
948 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 110
949 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 120
950 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 130
951 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 140
952 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 150
953 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 160
954 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 170
955 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 180
956 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 190
957 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 200
958 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 210
959 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 220
960 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 230
961 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 240
962 OOR, OOR, OOR, OOR, OOR, OOR // 250
965 __attribute__((__aligned__(16))) constexpr uint16_t shift10[] = {
966 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 0-9
967 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 10
968 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 20
969 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 30
970 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, 0, // 40
971 10, 20, 30, 40, 50, 60, 70, 80, 90, OOR, OOR,
972 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 60
973 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 70
974 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 80
975 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 90
976 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 100
977 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 110
978 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 120
979 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 130
980 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 140
981 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 150
982 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 160
983 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 170
984 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 180
985 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 190
986 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 200
987 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 210
988 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 220
989 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 230
990 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 240
991 OOR, OOR, OOR, OOR, OOR, OOR // 250
994 __attribute__((__aligned__(16))) constexpr uint16_t shift100[] = {
995 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 0-9
996 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 10
997 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 20
998 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 30
999 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, 0, // 40
1000 100, 200, 300, 400, 500, 600, 700, 800, 900, OOR, OOR,
1001 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 60
1002 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 70
1003 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 80
1004 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 90
1005 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 100
1006 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 110
1007 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 120
1008 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 130
1009 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 140
1010 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 150
1011 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 160
1012 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 170
1013 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 180
1014 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 190
1015 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 200
1016 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 210
1017 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 220
1018 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 230
1019 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 240
1020 OOR, OOR, OOR, OOR, OOR, OOR // 250
1023 __attribute__((__aligned__(16))) constexpr uint16_t shift1000[] = {
1024 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 0-9
1025 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 10
1026 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 20
1027 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 30
1028 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, 0, // 40
1029 1000, 2000, 3000, 4000, 5000, 6000, 7000, 8000, 9000, OOR, OOR,
1030 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 60
1031 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 70
1032 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 80
1033 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 90
1034 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 100
1035 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 110
1036 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 120
1037 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 130
1038 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 140
1039 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 150
1040 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 160
1041 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 170
1042 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 180
1043 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 190
1044 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 200
1045 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 210
1046 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 220
1047 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 230
1048 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 240
1049 OOR, OOR, OOR, OOR, OOR, OOR // 250
1053 * String represented as a pair of pointers to char to unsigned
1054 * integrals. Assumes NO whitespace before or after, and also that the
1055 * string is composed entirely of digits. Tgt must be unsigned, and no
1056 * sign is allowed in the string (even it's '+'). String may be empty,
1057 * in which case digits_to throws.
1059 template <class Tgt>
1060 Tgt digits_to(const char * b, const char * e) {
1062 static_assert(!std::is_signed<Tgt>::value, "Unsigned type expected");
1065 const size_t size = e - b;
1067 /* Although the string is entirely made of digits, we still need to
1068 * check for overflow.
1070 if (size >= std::numeric_limits<Tgt>::digits10 + 1) {
1071 // Leading zeros? If so, recurse to keep things simple
1072 if (b < e && *b == '0') {
1074 if (b == e) return 0; // just zeros, e.g. "0000"
1075 if (*b != '0') return digits_to<Tgt>(b, e);
1078 FOLLY_RANGE_CHECK(size == std::numeric_limits<Tgt>::digits10 + 1 &&
1079 strncmp(b, detail::MaxString<Tgt>::value, size) <= 0,
1080 "Numeric overflow upon conversion");
1083 // Here we know that the number won't overflow when
1084 // converted. Proceed without checks.
1088 for (; e - b >= 4; b += 4) {
1090 const int32_t r0 = shift1000[static_cast<size_t>(b[0])];
1091 const int32_t r1 = shift100[static_cast<size_t>(b[1])];
1092 const int32_t r2 = shift10[static_cast<size_t>(b[2])];
1093 const int32_t r3 = shift1[static_cast<size_t>(b[3])];
1094 const auto sum = r0 + r1 + r2 + r3;
1095 assert(sum < OOR && "Assumption: string only has digits");
1101 const int32_t r0 = shift100[static_cast<size_t>(b[0])];
1102 const int32_t r1 = shift10[static_cast<size_t>(b[1])];
1103 const int32_t r2 = shift1[static_cast<size_t>(b[2])];
1104 const auto sum = r0 + r1 + r2;
1105 assert(sum < OOR && "Assumption: string only has digits");
1106 return result * 1000 + sum;
1109 const int32_t r0 = shift10[static_cast<size_t>(b[0])];
1110 const int32_t r1 = shift1[static_cast<size_t>(b[1])];
1111 const auto sum = r0 + r1;
1112 assert(sum < OOR && "Assumption: string only has digits");
1113 return result * 100 + sum;
1116 const int32_t sum = shift1[static_cast<size_t>(b[0])];
1117 assert(sum < OOR && "Assumption: string only has digits");
1118 return result * 10 + sum;
1123 FOLLY_RANGE_CHECK(size > 0, "Found no digits to convert in input");
1128 bool str_to_bool(StringPiece * src);
1130 } // namespace detail
1133 * String represented as a pair of pointers to char to unsigned
1134 * integrals. Assumes NO whitespace before or after.
1136 template <class Tgt>
1137 typename std::enable_if<
1138 std::is_integral<Tgt>::value && !std::is_signed<Tgt>::value
1139 && !std::is_same<typename std::remove_cv<Tgt>::type, bool>::value,
1141 to(const char * b, const char * e) {
1142 return detail::digits_to<Tgt>(b, e);
1146 * String represented as a pair of pointers to char to signed
1147 * integrals. Assumes NO whitespace before or after. Allows an
1148 * optional leading sign.
1150 template <class Tgt>
1151 typename std::enable_if<
1152 std::is_integral<Tgt>::value && std::is_signed<Tgt>::value,
1154 to(const char * b, const char * e) {
1155 FOLLY_RANGE_CHECK(b < e, "Empty input string in conversion to integral");
1158 Tgt result = -to<typename std::make_unsigned<Tgt>::type>(b + 1, e);
1159 FOLLY_RANGE_CHECK(result <= 0, "Negative overflow.");
1162 FOLLY_RANGE_CHECK(*b == '+', "Invalid lead character");
1165 Tgt result = to<typename std::make_unsigned<Tgt>::type>(b, e);
1166 FOLLY_RANGE_CHECK(result >= 0, "Overflow.");
1171 * Parsing strings to integrals. These routines differ from
1172 * to<integral>(string) in that they take a POINTER TO a StringPiece
1173 * and alter that StringPiece to reflect progress information.
1177 * StringPiece to integrals, with progress information. Alters the
1178 * StringPiece parameter to munch the already-parsed characters.
1180 template <class Tgt>
1181 typename std::enable_if<
1182 std::is_integral<Tgt>::value
1183 && !std::is_same<typename std::remove_cv<Tgt>::type, bool>::value,
1185 to(StringPiece * src) {
1187 auto b = src->data(), past = src->data() + src->size();
1189 FOLLY_RANGE_CHECK(b < past, "No digits found in input string");
1190 if (!isspace(*b)) break;
1195 // First digit is customized because we test for sign
1196 bool negative = false;
1197 /* static */ if (std::is_signed<Tgt>::value) {
1202 FOLLY_RANGE_CHECK(*m == '+', "Invalid leading character in conversion"
1209 FOLLY_RANGE_CHECK(m < past, "No digits found in input string");
1210 FOLLY_RANGE_CHECK(isdigit(*m), "Non-digit character found");
1211 m = detail::findFirstNonDigit<Tgt>(m + 1, past);
1214 /* static */ if (!std::is_signed<Tgt>::value) {
1215 result = detail::digits_to<typename std::make_unsigned<Tgt>::type>(b, m);
1217 auto t = detail::digits_to<typename std::make_unsigned<Tgt>::type>(b, m);
1220 FOLLY_RANGE_CHECK(is_non_positive(result), "Negative overflow");
1223 FOLLY_RANGE_CHECK(is_non_negative(result), "Overflow");
1226 src->advance(m - src->data());
1231 * StringPiece to bool, with progress information. Alters the
1232 * StringPiece parameter to munch the already-parsed characters.
1234 template <class Tgt>
1235 typename std::enable_if<
1236 std::is_same<typename std::remove_cv<Tgt>::type, bool>::value,
1238 to(StringPiece * src) {
1239 return detail::str_to_bool(src);
1245 * Enforce that the suffix following a number is made up only of whitespace.
1247 inline void enforceWhitespace(const char* b, const char* e) {
1248 for (; b != e; ++b) {
1249 FOLLY_RANGE_CHECK(isspace(*b), to<std::string>("Non-whitespace: ", *b));
1253 } // namespace detail
1256 * String or StringPiece to integrals. Accepts leading and trailing
1257 * whitespace, but no non-space trailing characters.
1259 template <class Tgt>
1260 typename std::enable_if<
1261 std::is_integral<Tgt>::value,
1263 to(StringPiece src) {
1264 Tgt result = to<Tgt>(&src);
1265 detail::enforceWhitespace(src.data(), src.data() + src.size());
1269 /*******************************************************************************
1270 * Conversions from string types to floating-point types.
1271 ******************************************************************************/
1274 * StringPiece to double, with progress information. Alters the
1275 * StringPiece parameter to munch the already-parsed characters.
1277 template <class Tgt>
1278 inline typename std::enable_if<
1279 std::is_floating_point<Tgt>::value,
1281 to(StringPiece *const src) {
1282 using namespace double_conversion;
1283 static StringToDoubleConverter
1284 conv(StringToDoubleConverter::ALLOW_TRAILING_JUNK
1285 | StringToDoubleConverter::ALLOW_LEADING_SPACES,
1287 // return this for junk input string
1288 std::numeric_limits<double>::quiet_NaN(),
1291 FOLLY_RANGE_CHECK(!src->empty(), "No digits found in input string");
1294 auto result = conv.StringToDouble(src->data(),
1295 static_cast<int>(src->size()),
1296 &length); // processed char count
1298 if (!std::isnan(result)) {
1299 src->advance(length);
1303 for (;; src->advance(1)) {
1305 throw std::range_error("Unable to convert an empty string"
1306 " to a floating point value.");
1308 if (!isspace(src->front())) {
1313 // Was that "inf[inity]"?
1314 if (src->size() >= 3 && toupper((*src)[0]) == 'I'
1315 && toupper((*src)[1]) == 'N' && toupper((*src)[2]) == 'F') {
1316 if (src->size() >= 8 &&
1317 toupper((*src)[3]) == 'I' &&
1318 toupper((*src)[4]) == 'N' &&
1319 toupper((*src)[5]) == 'I' &&
1320 toupper((*src)[6]) == 'T' &&
1321 toupper((*src)[7]) == 'Y') {
1326 return std::numeric_limits<Tgt>::infinity();
1329 // Was that "-inf[inity]"?
1330 if (src->size() >= 4 && toupper((*src)[0]) == '-'
1331 && toupper((*src)[1]) == 'I' && toupper((*src)[2]) == 'N'
1332 && toupper((*src)[3]) == 'F') {
1333 if (src->size() >= 9 &&
1334 toupper((*src)[4]) == 'I' &&
1335 toupper((*src)[5]) == 'N' &&
1336 toupper((*src)[6]) == 'I' &&
1337 toupper((*src)[7]) == 'T' &&
1338 toupper((*src)[8]) == 'Y') {
1343 return -std::numeric_limits<Tgt>::infinity();
1347 if (src->size() >= 3 && toupper((*src)[0]) == 'N'
1348 && toupper((*src)[1]) == 'A' && toupper((*src)[2]) == 'N') {
1350 return std::numeric_limits<Tgt>::quiet_NaN();
1354 if (src->size() >= 4 &&
1355 toupper((*src)[0]) == '-' &&
1356 toupper((*src)[1]) == 'N' &&
1357 toupper((*src)[2]) == 'A' &&
1358 toupper((*src)[3]) == 'N') {
1360 return -std::numeric_limits<Tgt>::quiet_NaN();
1364 throw std::range_error("Unable to convert \"" + src->toString()
1365 + "\" to a floating point value.");
1369 * Any string, const char*, or StringPiece to double.
1371 template <class Tgt>
1372 typename std::enable_if<
1373 std::is_floating_point<Tgt>::value,
1375 to(StringPiece src) {
1376 Tgt result = to<double>(&src);
1377 detail::enforceWhitespace(src.data(), src.data() + src.size());
1381 /*******************************************************************************
1382 * Integral to floating point and back
1383 ******************************************************************************/
1386 * Checked conversion from integral to flating point and back. The
1387 * result must be convertible back to the source type without loss of
1388 * precision. This seems Draconian but sometimes is what's needed, and
1389 * complements existing routines nicely. For various rounding
1390 * routines, see <math>.
1392 template <class Tgt, class Src>
1393 typename std::enable_if<
1394 (std::is_integral<Src>::value && std::is_floating_point<Tgt>::value)
1396 (std::is_floating_point<Src>::value && std::is_integral<Tgt>::value),
1398 to(const Src & value) {
1400 auto witness = static_cast<Src>(result);
1401 if (value != witness) {
1402 throw std::range_error(
1403 to<std::string>("to<>: loss of precision when converting ", value,
1404 " to type ", typeid(Tgt).name()).c_str());
1409 /*******************************************************************************
1410 * Enum to anything and back
1411 ******************************************************************************/
1413 #if defined(__clang__) || __GNUC_PREREQ(4, 7)
1414 // std::underlying_type became available by gcc 4.7.0
1416 template <class Tgt, class Src>
1417 typename std::enable_if<
1418 std::is_enum<Src>::value && !std::is_same<Src, Tgt>::value, Tgt>::type
1419 to(const Src & value) {
1420 return to<Tgt>(static_cast<typename std::underlying_type<Src>::type>(value));
1423 template <class Tgt, class Src>
1424 typename std::enable_if<
1425 std::is_enum<Tgt>::value && !std::is_same<Src, Tgt>::value, Tgt>::type
1426 to(const Src & value) {
1427 return static_cast<Tgt>(to<typename std::underlying_type<Tgt>::type>(value));
1432 template <class Tgt, class Src>
1433 typename std::enable_if<
1434 std::is_enum<Src>::value && !std::is_same<Src, Tgt>::value, Tgt>::type
1435 to(const Src & value) {
1436 /* static */ if (Src(-1) < 0) {
1437 /* static */ if (sizeof(Src) <= sizeof(int)) {
1438 return to<Tgt>(static_cast<int>(value));
1440 return to<Tgt>(static_cast<long>(value));
1443 /* static */ if (sizeof(Src) <= sizeof(int)) {
1444 return to<Tgt>(static_cast<unsigned int>(value));
1446 return to<Tgt>(static_cast<unsigned long>(value));
1451 template <class Tgt, class Src>
1452 typename std::enable_if<
1453 std::is_enum<Tgt>::value && !std::is_same<Src, Tgt>::value, Tgt>::type
1454 to(const Src & value) {
1455 /* static */ if (Tgt(-1) < 0) {
1456 /* static */ if (sizeof(Tgt) <= sizeof(int)) {
1457 return static_cast<Tgt>(to<int>(value));
1459 return static_cast<Tgt>(to<long>(value));
1462 /* static */ if (sizeof(Tgt) <= sizeof(int)) {
1463 return static_cast<Tgt>(to<unsigned int>(value));
1465 return static_cast<Tgt>(to<unsigned long>(value));
1470 #endif // gcc 4.7 onwards
1472 } // namespace folly
1474 // FOLLY_CONV_INTERNAL is defined by Conv.cpp. Keep the FOLLY_RANGE_CHECK
1475 // macro for use in Conv.cpp, but #undefine it everywhere else we are included,
1476 // to avoid defining this global macro name in other files that include Conv.h.
1477 #ifndef FOLLY_CONV_INTERNAL
1478 #undef FOLLY_RANGE_CHECK
1479 #undef FOLLY_RANGE_CHECK_STRINGIZE2
1480 #undef FOLLY_RANGE_CHECK_STRINGIZE
1483 #endif /* FOLLY_BASE_CONV_H_ */