2 * Copyright 2015 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 // Android doesn't support std::to_string so just use a placeholder there.
51 #define FOLLY_RANGE_CHECK_TO_STRING(x) std::string("N/A")
53 #define FOLLY_RANGE_CHECK_TO_STRING(x) std::to_string(x)
56 #define FOLLY_RANGE_CHECK(condition, message, src) \
57 ((condition) ? (void)0 : throw std::range_error( \
58 (std::string(__FILE__ "(" FOLLY_RANGE_CHECK_STRINGIZE2(__LINE__) "): ") \
59 + (message) + ": '" + (src) + "'").c_str()))
61 #define FOLLY_RANGE_CHECK_BEGIN_END(condition, message, b, e) \
62 FOLLY_RANGE_CHECK(condition, message, std::string((b), (e) - (b)))
64 #define FOLLY_RANGE_CHECK_STRINGPIECE(condition, message, sp) \
65 FOLLY_RANGE_CHECK(condition, message, std::string((sp).data(), (sp).size()))
70 * The identity conversion function.
71 * to<T>(T) returns itself for all types T.
73 template <class Tgt, class Src>
74 typename std::enable_if<std::is_same<Tgt, Src>::value, Tgt>::type
75 to(const Src & value) {
79 template <class Tgt, class Src>
80 typename std::enable_if<std::is_same<Tgt, Src>::value, Tgt>::type
82 return std::move(value);
85 /*******************************************************************************
86 * Integral to integral
87 ******************************************************************************/
90 * Checked conversion from integral to integral. The checks are only
91 * performed when meaningful, e.g. conversion from int to long goes
94 template <class Tgt, class Src>
95 typename std::enable_if<
96 std::is_integral<Src>::value
97 && std::is_integral<Tgt>::value
98 && !std::is_same<Tgt, Src>::value,
100 to(const Src & value) {
101 /* static */ if (std::numeric_limits<Tgt>::max()
102 < std::numeric_limits<Src>::max()) {
104 (!greater_than<Tgt, std::numeric_limits<Tgt>::max()>(value)),
106 FOLLY_RANGE_CHECK_TO_STRING(value));
108 /* static */ if (std::is_signed<Src>::value &&
109 (!std::is_signed<Tgt>::value || sizeof(Src) > sizeof(Tgt))) {
111 (!less_than<Tgt, std::numeric_limits<Tgt>::min()>(value)),
113 FOLLY_RANGE_CHECK_TO_STRING(value));
115 return static_cast<Tgt>(value);
118 /*******************************************************************************
119 * Floating point to floating point
120 ******************************************************************************/
122 template <class Tgt, class Src>
123 typename std::enable_if<
124 std::is_floating_point<Tgt>::value
125 && std::is_floating_point<Src>::value
126 && !std::is_same<Tgt, Src>::value,
128 to(const Src & value) {
129 /* static */ if (std::numeric_limits<Tgt>::max() <
130 std::numeric_limits<Src>::max()) {
131 FOLLY_RANGE_CHECK(value <= std::numeric_limits<Tgt>::max(),
133 FOLLY_RANGE_CHECK_TO_STRING(value));
134 FOLLY_RANGE_CHECK(value >= -std::numeric_limits<Tgt>::max(),
136 FOLLY_RANGE_CHECK_TO_STRING(value));
138 return boost::implicit_cast<Tgt>(value);
141 /*******************************************************************************
143 ******************************************************************************/
148 const T& getLastElement(const T & v) {
152 template <class T, class... Ts>
153 typename std::tuple_element<
155 std::tuple<T, Ts...> >::type const&
156 getLastElement(const T& v, const Ts&... vs) {
157 return getLastElement(vs...);
160 // This class exists to specialize away std::tuple_element in the case where we
161 // have 0 template arguments. Without this, Clang/libc++ will blow a
162 // static_assert even if tuple_element is protected by an enable_if.
163 template <class... Ts>
164 struct last_element {
165 typedef typename std::enable_if<
167 typename std::tuple_element<
168 sizeof...(Ts) - 1, std::tuple<Ts...>
173 struct last_element<> {
177 } // namespace detail
179 /*******************************************************************************
180 * Conversions from integral types to string types.
181 ******************************************************************************/
183 #if FOLLY_HAVE_INT128_T
186 template <typename IntegerType>
187 constexpr unsigned int
189 return ceil((double(sizeof(IntegerType) * CHAR_BIT) * M_LN2) / M_LN10);
193 unsafeTelescope128(char * buffer, size_t room, unsigned __int128 x) {
194 typedef unsigned __int128 Usrc;
197 while (x >= (Usrc(1) << 64)) { // Using 128-bit division while needed
198 const auto y = x / 10;
199 const auto digit = x % 10;
201 buffer[p--] = '0' + digit;
205 uint64_t xx = x; // Moving to faster 64-bit division thereafter
208 const auto y = xx / 10ULL;
209 const auto digit = xx % 10ULL;
211 buffer[p--] = '0' + digit;
215 buffer[p] = '0' + xx;
224 * Returns the number of digits in the base 10 representation of an
225 * uint64_t. Useful for preallocating buffers and such. It's also used
226 * internally, see below. Measurements suggest that defining a
227 * separate overload for 32-bit integers is not worthwhile.
230 inline uint32_t digits10(uint64_t v) {
233 // For this arch we can get a little help from specialized CPU instructions
234 // which can count leading zeroes; 64 minus that is appx. log (base 2).
235 // Use that to approximate base-10 digits (log_10) and then adjust if needed.
237 // 10^i, defined for i 0 through 19.
238 // This is 20 * 8 == 160 bytes, which fits neatly into 5 cache lines
239 // (assuming a cache line size of 64).
240 static const uint64_t powersOf10[20] __attribute__((__aligned__(64))) = {
241 1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000,
242 10000000000, 100000000000, 1000000000000, 10000000000000, 100000000000000,
243 1000000000000000, 10000000000000000, 100000000000000000,
244 1000000000000000000, 10000000000000000000UL
247 // "count leading zeroes" operation not valid; for 0; special case this.
252 // bits is in the ballpark of log_2(v).
253 const uint8_t leadingZeroes = __builtin_clzll(v);
254 const auto bits = 63 - leadingZeroes;
256 // approximate log_10(v) == log_10(2) * bits.
257 // Integer magic below: 77/256 is appx. 0.3010 (log_10(2)).
258 // The +1 is to make this the ceiling of the log_10 estimate.
259 const uint32_t minLength = 1 + ((bits * 77) >> 8);
261 // return that log_10 lower bound, plus adjust if input >= 10^(that bound)
262 // in case there's a small error and we misjudged length.
263 return minLength + (uint32_t) (UNLIKELY (v >= powersOf10[minLength]));
269 if (LIKELY(v < 10)) return result;
270 if (LIKELY(v < 100)) return result + 1;
271 if (LIKELY(v < 1000)) return result + 2;
272 if (LIKELY(v < 10000)) return result + 3;
273 // Skip ahead by 4 orders of magnitude
282 * Copies the ASCII base 10 representation of v into buffer and
283 * returns the number of bytes written. Does NOT append a \0. Assumes
284 * the buffer points to digits10(v) bytes of valid memory. Note that
285 * uint64 needs at most 20 bytes, uint32_t needs at most 10 bytes,
286 * uint16_t needs at most 5 bytes, and so on. Measurements suggest
287 * that defining a separate overload for 32-bit integers is not
290 * This primitive is unsafe because it makes the size assumption and
291 * because it does not add a terminating \0.
294 inline uint32_t uint64ToBufferUnsafe(uint64_t v, char *const buffer) {
295 auto const result = digits10(v);
296 // WARNING: using size_t or pointer arithmetic for pos slows down
297 // the loop below 20x. This is because several 32-bit ops can be
298 // done in parallel, but only fewer 64-bit ones.
299 uint32_t pos = result - 1;
301 // Keep these together so a peephole optimization "sees" them and
302 // computes them in one shot.
303 auto const q = v / 10;
304 auto const r = static_cast<uint32_t>(v % 10);
305 buffer[pos--] = '0' + r;
308 // Last digit is trivial to handle
309 buffer[pos] = static_cast<uint32_t>(v) + '0';
314 * A single char gets appended.
317 void toAppend(char value, Tgt * result) {
322 constexpr typename std::enable_if<
323 std::is_same<T, char>::value,
325 estimateSpaceNeeded(T) {
330 * Ubiquitous helper template for writing string appenders
332 template <class T> struct IsSomeString {
333 enum { value = std::is_same<T, std::string>::value
334 || std::is_same<T, fbstring>::value };
338 * Everything implicitly convertible to const char* gets appended.
340 template <class Tgt, class Src>
341 typename std::enable_if<
342 std::is_convertible<Src, const char*>::value
343 && IsSomeString<Tgt>::value>::type
344 toAppend(Src value, Tgt * result) {
345 // Treat null pointers like an empty string, as in:
346 // operator<<(std::ostream&, const char*).
347 const char* c = value;
349 result->append(value);
354 typename std::enable_if<
355 std::is_convertible<Src, const char*>::value,
357 estimateSpaceNeeded(Src value) {
358 const char *c = value;
360 return folly::StringPiece(value).size();
366 typename std::enable_if<
367 (std::is_convertible<Src, folly::StringPiece>::value ||
368 IsSomeString<Src>::value) &&
369 !std::is_convertible<Src, const char*>::value,
371 estimateSpaceNeeded(Src value) {
372 return folly::StringPiece(value).size();
376 typename std::enable_if<
377 std::is_pointer<Src>::value &&
378 IsSomeString<std::remove_pointer<Src>>::value,
380 estimateSpaceNeeded(Src value) {
381 return value->size();
385 * Strings get appended, too.
387 template <class Tgt, class Src>
388 typename std::enable_if<
389 IsSomeString<Src>::value && IsSomeString<Tgt>::value>::type
390 toAppend(const Src& value, Tgt * result) {
391 result->append(value);
395 * and StringPiece objects too
398 typename std::enable_if<
399 IsSomeString<Tgt>::value>::type
400 toAppend(StringPiece value, Tgt * result) {
401 result->append(value.data(), value.size());
405 * There's no implicit conversion from fbstring to other string types,
406 * so make a specialization.
409 typename std::enable_if<
410 IsSomeString<Tgt>::value>::type
411 toAppend(const fbstring& value, Tgt * result) {
412 result->append(value.data(), value.size());
415 #if FOLLY_HAVE_INT128_T
417 * Special handling for 128 bit integers.
422 toAppend(__int128 value, Tgt * result) {
423 typedef unsigned __int128 Usrc;
424 char buffer[detail::digitsEnough<unsigned __int128>() + 1];
428 p = detail::unsafeTelescope128(buffer, sizeof(buffer), Usrc(-value));
431 p = detail::unsafeTelescope128(buffer, sizeof(buffer), value);
434 result->append(buffer + p, buffer + sizeof(buffer));
439 toAppend(unsigned __int128 value, Tgt * result) {
440 char buffer[detail::digitsEnough<unsigned __int128>()];
443 p = detail::unsafeTelescope128(buffer, sizeof(buffer), value);
445 result->append(buffer + p, buffer + sizeof(buffer));
449 constexpr typename std::enable_if<
450 std::is_same<T, __int128>::value,
452 estimateSpaceNeeded(T) {
453 return detail::digitsEnough<__int128>();
457 constexpr typename std::enable_if<
458 std::is_same<T, unsigned __int128>::value,
460 estimateSpaceNeeded(T) {
461 return detail::digitsEnough<unsigned __int128>();
467 * int32_t and int64_t to string (by appending) go through here. The
468 * result is APPENDED to a preexisting string passed as the second
469 * parameter. This should be efficient with fbstring because fbstring
470 * incurs no dynamic allocation below 23 bytes and no number has more
471 * than 22 bytes in its textual representation (20 for digits, one for
472 * sign, one for the terminating 0).
474 template <class Tgt, class Src>
475 typename std::enable_if<
476 std::is_integral<Src>::value && std::is_signed<Src>::value &&
477 IsSomeString<Tgt>::value && sizeof(Src) >= 4>::type
478 toAppend(Src value, Tgt * result) {
481 result->push_back('-');
482 result->append(buffer, uint64ToBufferUnsafe(-uint64_t(value), buffer));
484 result->append(buffer, uint64ToBufferUnsafe(value, buffer));
489 typename std::enable_if<
490 std::is_integral<Src>::value && std::is_signed<Src>::value
491 && sizeof(Src) >= 4 && sizeof(Src) < 16,
493 estimateSpaceNeeded(Src value) {
495 return 1 + digits10(static_cast<uint64_t>(-value));
498 return digits10(static_cast<uint64_t>(value));
502 * As above, but for uint32_t and uint64_t.
504 template <class Tgt, class Src>
505 typename std::enable_if<
506 std::is_integral<Src>::value && !std::is_signed<Src>::value
507 && IsSomeString<Tgt>::value && sizeof(Src) >= 4>::type
508 toAppend(Src value, Tgt * result) {
510 result->append(buffer, buffer + uint64ToBufferUnsafe(value, buffer));
514 typename std::enable_if<
515 std::is_integral<Src>::value && !std::is_signed<Src>::value
516 && sizeof(Src) >= 4 && sizeof(Src) < 16,
518 estimateSpaceNeeded(Src value) {
519 return digits10(value);
523 * All small signed and unsigned integers to string go through 32-bit
524 * types int32_t and uint32_t, respectively.
526 template <class Tgt, class Src>
527 typename std::enable_if<
528 std::is_integral<Src>::value
529 && IsSomeString<Tgt>::value && sizeof(Src) < 4>::type
530 toAppend(Src value, Tgt * result) {
532 std::conditional<std::is_signed<Src>::value, int64_t, uint64_t>::type
534 toAppend<Tgt>(static_cast<Intermediate>(value), result);
538 typename std::enable_if<
539 std::is_integral<Src>::value
541 && !std::is_same<Src, char>::value,
543 estimateSpaceNeeded(Src value) {
545 std::conditional<std::is_signed<Src>::value, int64_t, uint64_t>::type
547 return estimateSpaceNeeded(static_cast<Intermediate>(value));
550 #if defined(__clang__) || __GNUC_PREREQ(4, 7)
551 // std::underlying_type became available by gcc 4.7.0
554 * Enumerated values get appended as integers.
556 template <class Tgt, class Src>
557 typename std::enable_if<
558 std::is_enum<Src>::value && IsSomeString<Tgt>::value>::type
559 toAppend(Src value, Tgt * result) {
561 static_cast<typename std::underlying_type<Src>::type>(value), result);
565 typename std::enable_if<
566 std::is_enum<Src>::value, size_t>::type
567 estimateSpaceNeeded(Src value) {
568 return estimateSpaceNeeded(
569 static_cast<typename std::underlying_type<Src>::type>(value));
575 * Enumerated values get appended as integers.
577 template <class Tgt, class Src>
578 typename std::enable_if<
579 std::is_enum<Src>::value && IsSomeString<Tgt>::value>::type
580 toAppend(Src value, Tgt * result) {
581 /* static */ if (Src(-1) < 0) {
582 /* static */ if (sizeof(Src) <= sizeof(int)) {
583 toAppend(static_cast<int>(value), result);
585 toAppend(static_cast<long>(value), result);
588 /* static */ if (sizeof(Src) <= sizeof(int)) {
589 toAppend(static_cast<unsigned int>(value), result);
591 toAppend(static_cast<unsigned long>(value), result);
597 typename std::enable_if<
598 std::is_enum<Src>::value, size_t>::type
599 estimateSpaceNeeded(Src value) {
600 /* static */ if (Src(-1) < 0) {
601 /* static */ if (sizeof(Src) <= sizeof(int)) {
602 return estimateSpaceNeeded(static_cast<int>(value));
604 return estimateSpaceNeeded(static_cast<long>(value));
607 /* static */ if (sizeof(Src) <= sizeof(int)) {
608 return estimateSpaceNeeded(static_cast<unsigned int>(value));
610 return estimateSpaceNeeded(static_cast<unsigned long>(value));
615 #endif // gcc 4.7 onwards
617 /*******************************************************************************
618 * Conversions from floating-point types to string types.
619 ******************************************************************************/
622 constexpr int kConvMaxDecimalInShortestLow = -6;
623 constexpr int kConvMaxDecimalInShortestHigh = 21;
626 /** Wrapper around DoubleToStringConverter **/
627 template <class Tgt, class Src>
628 typename std::enable_if<
629 std::is_floating_point<Src>::value
630 && IsSomeString<Tgt>::value>::type
634 double_conversion::DoubleToStringConverter::DtoaMode mode,
635 unsigned int numDigits) {
636 using namespace double_conversion;
637 DoubleToStringConverter
638 conv(DoubleToStringConverter::NO_FLAGS,
639 "infinity", "NaN", 'E',
640 detail::kConvMaxDecimalInShortestLow,
641 detail::kConvMaxDecimalInShortestHigh,
642 6, // max leading padding zeros
643 1); // max trailing padding zeros
645 StringBuilder builder(buffer, sizeof(buffer));
647 case DoubleToStringConverter::SHORTEST:
648 conv.ToShortest(value, &builder);
650 case DoubleToStringConverter::FIXED:
651 conv.ToFixed(value, numDigits, &builder);
654 CHECK(mode == DoubleToStringConverter::PRECISION);
655 conv.ToPrecision(value, numDigits, &builder);
658 const size_t length = builder.position();
660 result->append(buffer, length);
664 * As above, but for floating point
666 template <class Tgt, class Src>
667 typename std::enable_if<
668 std::is_floating_point<Src>::value
669 && IsSomeString<Tgt>::value>::type
670 toAppend(Src value, Tgt * result) {
672 value, result, double_conversion::DoubleToStringConverter::SHORTEST, 0);
676 * Upper bound of the length of the output from
677 * DoubleToStringConverter::ToShortest(double, StringBuilder*),
678 * as used in toAppend(double, string*).
681 typename std::enable_if<
682 std::is_floating_point<Src>::value, size_t>::type
683 estimateSpaceNeeded(Src value) {
684 // kBase10MaximalLength is 17. We add 1 for decimal point,
685 // e.g. 10.0/9 is 17 digits and 18 characters, including the decimal point.
686 constexpr int kMaxMantissaSpace =
687 double_conversion::DoubleToStringConverter::kBase10MaximalLength + 1;
688 // strlen("E-") + digits10(numeric_limits<double>::max_exponent10)
689 constexpr int kMaxExponentSpace = 2 + 3;
690 static const int kMaxPositiveSpace = std::max({
691 // E.g. 1.1111111111111111E-100.
692 kMaxMantissaSpace + kMaxExponentSpace,
693 // E.g. 0.000001.1111111111111111, if kConvMaxDecimalInShortestLow is -6.
694 kMaxMantissaSpace - detail::kConvMaxDecimalInShortestLow,
695 // If kConvMaxDecimalInShortestHigh is 21, then 1e21 is the smallest
696 // number > 1 which ToShortest outputs in exponential notation,
697 // so 21 is the longest non-exponential number > 1.
698 detail::kConvMaxDecimalInShortestHigh
700 return kMaxPositiveSpace + (value < 0); // +1 for minus sign, if negative
704 * This can be specialized, together with adding specialization
705 * for estimateSpaceNeed for your type, so that we allocate
706 * as much as you need instead of the default
709 struct HasLengthEstimator : std::false_type {};
712 constexpr typename std::enable_if<
713 !std::is_fundamental<Src>::value
714 #ifdef FOLLY_HAVE_INT128_T
715 // On OSX 10.10, is_fundamental<__int128> is false :-O
716 && !std::is_same<__int128, Src>::value
717 && !std::is_same<unsigned __int128, Src>::value
719 && !IsSomeString<Src>::value
720 && !std::is_convertible<Src, const char*>::value
721 && !std::is_convertible<Src, StringPiece>::value
722 && !std::is_enum<Src>::value
723 && !HasLengthEstimator<Src>::value,
725 estimateSpaceNeeded(const Src&) {
726 return sizeof(Src) + 1; // dumbest best effort ever?
731 inline size_t estimateSpaceToReserve(size_t sofar) {
735 template <class T, class... Ts>
736 size_t estimateSpaceToReserve(size_t sofar, const T& v, const Ts&... vs) {
737 return estimateSpaceToReserve(sofar + estimateSpaceNeeded(v), vs...);
741 size_t estimateSpaceToReserve(size_t sofar, const T& v) {
742 return sofar + estimateSpaceNeeded(v);
746 void reserveInTarget(const Ts&...vs) {
747 getLastElement(vs...)->reserve(estimateSpaceToReserve(0, vs...));
750 template<class Delimiter, class...Ts>
751 void reserveInTargetDelim(const Delimiter& d, const Ts&...vs) {
752 static_assert(sizeof...(vs) >= 2, "Needs at least 2 args");
753 size_t fordelim = (sizeof...(vs) - 2) * estimateSpaceToReserve(0, d);
754 getLastElement(vs...)->reserve(estimateSpaceToReserve(fordelim, vs...));
758 * Variadic base case: append one element
760 template <class T, class Tgt>
761 typename std::enable_if<
762 IsSomeString<typename std::remove_pointer<Tgt>::type>
764 toAppendStrImpl(const T& v, Tgt result) {
768 template <class T, class... Ts>
769 typename std::enable_if<sizeof...(Ts) >= 2
771 typename std::remove_pointer<
772 typename detail::last_element<Ts...>::type
773 >::type>::value>::type
774 toAppendStrImpl(const T& v, const Ts&... vs) {
775 toAppend(v, getLastElement(vs...));
776 toAppendStrImpl(vs...);
779 template <class Delimiter, class T, class Tgt>
780 typename std::enable_if<
781 IsSomeString<typename std::remove_pointer<Tgt>::type>
783 toAppendDelimStrImpl(const Delimiter& delim, const T& v, Tgt result) {
787 template <class Delimiter, class T, class... Ts>
788 typename std::enable_if<sizeof...(Ts) >= 2
790 typename std::remove_pointer<
791 typename detail::last_element<Ts...>::type
792 >::type>::value>::type
793 toAppendDelimStrImpl(const Delimiter& delim, const T& v, const Ts&... vs) {
794 // we are really careful here, calling toAppend with just one element does
795 // not try to estimate space needed (as we already did that). If we call
796 // toAppend(v, delim, ....) we would do unnecesary size calculation
797 toAppend(v, detail::getLastElement(vs...));
798 toAppend(delim, detail::getLastElement(vs...));
799 toAppendDelimStrImpl(delim, vs...);
805 * Variadic conversion to string. Appends each element in turn.
806 * If we have two or more things to append, we it will not reserve
807 * the space for them and will depend on strings exponential growth.
808 * If you just append once consider using toAppendFit which reserves
809 * the space needed (but does not have exponential as a result).
811 template <class... Ts>
812 typename std::enable_if<sizeof...(Ts) >= 3
814 typename std::remove_pointer<
815 typename detail::last_element<Ts...>::type
816 >::type>::value>::type
817 toAppend(const Ts&... vs) {
818 detail::toAppendStrImpl(vs...);
822 * Special version of the call that preallocates exaclty as much memory
823 * as need for arguments to be stored in target. This means we are
824 * not doing exponential growth when we append. If you are using it
825 * in a loop you are aiming at your foot with a big perf-destroying
827 * On the other hand if you are appending to a string once, this
828 * will probably save a few calls to malloc.
830 template <class... Ts>
831 typename std::enable_if<
833 typename std::remove_pointer<
834 typename detail::last_element<Ts...>::type
835 >::type>::value>::type
836 toAppendFit(const Ts&... vs) {
837 detail::reserveInTarget(vs...);
842 void toAppendFit(const Ts&) {}
845 * Variadic base case: do nothing.
848 typename std::enable_if<IsSomeString<Tgt>::value>::type
849 toAppend(Tgt* result) {
853 * Variadic base case: do nothing.
855 template <class Delimiter, class Tgt>
856 typename std::enable_if<IsSomeString<Tgt>::value>::type
857 toAppendDelim(const Delimiter& delim, Tgt* result) {
861 * 1 element: same as toAppend.
863 template <class Delimiter, class T, class Tgt>
864 typename std::enable_if<IsSomeString<Tgt>::value>::type
865 toAppendDelim(const Delimiter& delim, const T& v, Tgt* tgt) {
870 * Append to string with a delimiter in between elements. Check out
871 * comments for toAppend for details about memory allocation.
873 template <class Delimiter, class... Ts>
874 typename std::enable_if<sizeof...(Ts) >= 3
876 typename std::remove_pointer<
877 typename detail::last_element<Ts...>::type
878 >::type>::value>::type
879 toAppendDelim(const Delimiter& delim, const Ts&... vs) {
880 detail::toAppendDelimStrImpl(delim, vs...);
884 * Detail in comment for toAppendFit
886 template <class Delimiter, class... Ts>
887 typename std::enable_if<
889 typename std::remove_pointer<
890 typename detail::last_element<Ts...>::type
891 >::type>::value>::type
892 toAppendDelimFit(const Delimiter& delim, const Ts&... vs) {
893 detail::reserveInTargetDelim(delim, vs...);
894 toAppendDelim(delim, vs...);
897 template <class De, class Ts>
898 void toAppendDelimFit(const De&, const Ts&) {}
901 * to<SomeString>(v1, v2, ...) uses toAppend() (see below) as back-end
904 template <class Tgt, class... Ts>
905 typename std::enable_if<
906 IsSomeString<Tgt>::value && (
907 sizeof...(Ts) != 1 ||
908 !std::is_same<Tgt, typename detail::last_element<Ts...>::type>::value),
910 to(const Ts&... vs) {
912 toAppendFit(vs..., &result);
917 * toDelim<SomeString>(SomeString str) returns itself.
919 template <class Tgt, class Delim, class Src>
920 typename std::enable_if<
921 IsSomeString<Tgt>::value && std::is_same<Tgt, Src>::value,
923 toDelim(const Delim& delim, const Src & value) {
928 * toDelim<SomeString>(delim, v1, v2, ...) uses toAppendDelim() as
929 * back-end for all types.
931 template <class Tgt, class Delim, class... Ts>
932 typename std::enable_if<
933 IsSomeString<Tgt>::value && (
934 sizeof...(Ts) != 1 ||
935 !std::is_same<Tgt, typename detail::last_element<Ts...>::type>::value),
937 toDelim(const Delim& delim, const Ts&... vs) {
939 toAppendDelimFit(delim, vs..., &result);
943 /*******************************************************************************
944 * Conversions from string types to integral types.
945 ******************************************************************************/
950 * Finds the first non-digit in a string. The number of digits
951 * searched depends on the precision of the Tgt integral. Assumes the
952 * string starts with NO whitespace and NO sign.
954 * The semantics of the routine is:
956 * if (b >= e || !isdigit(*b)) return b;
959 * Complete unrolling marks bottom-line (i.e. entire conversion)
960 * improvements of 20%.
963 const char* findFirstNonDigit(const char* b, const char* e) {
965 auto const c = static_cast<unsigned>(*b) - '0';
971 // Maximum value of number when represented as a string
972 template <class T> struct MaxString {
973 static const char*const value;
978 * Lookup tables that converts from a decimal character value to an integral
979 * binary value, shifted by a decimal "shift" multiplier.
980 * For all character values in the range '0'..'9', the table at those
981 * index locations returns the actual decimal value shifted by the multiplier.
982 * For all other values, the lookup table returns an invalid OOR value.
984 // Out-of-range flag value, larger than the largest value that can fit in
985 // four decimal bytes (9999), but four of these added up together should
986 // still not overflow uint16_t.
987 constexpr int32_t OOR = 10000;
989 __attribute__((__aligned__(16))) constexpr uint16_t shift1[] = {
990 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 0-9
991 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 10
992 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 20
993 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 30
994 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, 0, // 40
995 1, 2, 3, 4, 5, 6, 7, 8, 9, OOR, OOR,
996 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 60
997 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 70
998 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 80
999 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 90
1000 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 100
1001 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 110
1002 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 120
1003 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 130
1004 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 140
1005 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 150
1006 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 160
1007 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 170
1008 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 180
1009 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 190
1010 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 200
1011 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 210
1012 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 220
1013 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 230
1014 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 240
1015 OOR, OOR, OOR, OOR, OOR, OOR // 250
1018 __attribute__((__aligned__(16))) constexpr uint16_t shift10[] = {
1019 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 0-9
1020 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 10
1021 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 20
1022 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 30
1023 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, 0, // 40
1024 10, 20, 30, 40, 50, 60, 70, 80, 90, OOR, OOR,
1025 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 60
1026 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 70
1027 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 80
1028 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 90
1029 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 100
1030 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 110
1031 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 120
1032 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 130
1033 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 140
1034 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 150
1035 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 160
1036 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 170
1037 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 180
1038 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 190
1039 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 200
1040 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 210
1041 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 220
1042 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 230
1043 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 240
1044 OOR, OOR, OOR, OOR, OOR, OOR // 250
1047 __attribute__((__aligned__(16))) constexpr uint16_t shift100[] = {
1048 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 0-9
1049 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 10
1050 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 20
1051 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 30
1052 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, 0, // 40
1053 100, 200, 300, 400, 500, 600, 700, 800, 900, OOR, OOR,
1054 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 60
1055 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 70
1056 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 80
1057 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 90
1058 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 100
1059 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 110
1060 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 120
1061 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 130
1062 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 140
1063 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 150
1064 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 160
1065 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 170
1066 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 180
1067 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 190
1068 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 200
1069 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 210
1070 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 220
1071 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 230
1072 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 240
1073 OOR, OOR, OOR, OOR, OOR, OOR // 250
1076 __attribute__((__aligned__(16))) constexpr uint16_t shift1000[] = {
1077 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 0-9
1078 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 10
1079 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 20
1080 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 30
1081 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, 0, // 40
1082 1000, 2000, 3000, 4000, 5000, 6000, 7000, 8000, 9000, OOR, OOR,
1083 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 60
1084 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 70
1085 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 80
1086 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 90
1087 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 100
1088 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 110
1089 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 120
1090 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 130
1091 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 140
1092 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 150
1093 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 160
1094 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 170
1095 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 180
1096 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 190
1097 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 200
1098 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 210
1099 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 220
1100 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 230
1101 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 240
1102 OOR, OOR, OOR, OOR, OOR, OOR // 250
1106 * String represented as a pair of pointers to char to unsigned
1107 * integrals. Assumes NO whitespace before or after, and also that the
1108 * string is composed entirely of digits. Tgt must be unsigned, and no
1109 * sign is allowed in the string (even it's '+'). String may be empty,
1110 * in which case digits_to throws.
1112 template <class Tgt>
1113 Tgt digits_to(const char * b, const char * e) {
1115 static_assert(!std::is_signed<Tgt>::value, "Unsigned type expected");
1118 const size_t size = e - b;
1120 /* Although the string is entirely made of digits, we still need to
1121 * check for overflow.
1123 if (size >= std::numeric_limits<Tgt>::digits10 + 1) {
1124 // Leading zeros? If so, recurse to keep things simple
1125 if (b < e && *b == '0') {
1127 if (b == e) return 0; // just zeros, e.g. "0000"
1128 if (*b != '0') return digits_to<Tgt>(b, e);
1131 FOLLY_RANGE_CHECK_BEGIN_END(
1132 size == std::numeric_limits<Tgt>::digits10 + 1 &&
1133 strncmp(b, detail::MaxString<Tgt>::value, size) <= 0,
1134 "Numeric overflow upon conversion", b, e);
1137 // Here we know that the number won't overflow when
1138 // converted. Proceed without checks.
1142 for (; e - b >= 4; b += 4) {
1144 const int32_t r0 = shift1000[static_cast<size_t>(b[0])];
1145 const int32_t r1 = shift100[static_cast<size_t>(b[1])];
1146 const int32_t r2 = shift10[static_cast<size_t>(b[2])];
1147 const int32_t r3 = shift1[static_cast<size_t>(b[3])];
1148 const auto sum = r0 + r1 + r2 + r3;
1149 assert(sum < OOR && "Assumption: string only has digits");
1155 const int32_t r0 = shift100[static_cast<size_t>(b[0])];
1156 const int32_t r1 = shift10[static_cast<size_t>(b[1])];
1157 const int32_t r2 = shift1[static_cast<size_t>(b[2])];
1158 const auto sum = r0 + r1 + r2;
1159 assert(sum < OOR && "Assumption: string only has digits");
1160 return result * 1000 + sum;
1163 const int32_t r0 = shift10[static_cast<size_t>(b[0])];
1164 const int32_t r1 = shift1[static_cast<size_t>(b[1])];
1165 const auto sum = r0 + r1;
1166 assert(sum < OOR && "Assumption: string only has digits");
1167 return result * 100 + sum;
1170 const int32_t sum = shift1[static_cast<size_t>(b[0])];
1171 assert(sum < OOR && "Assumption: string only has digits");
1172 return result * 10 + sum;
1177 FOLLY_RANGE_CHECK_BEGIN_END(size > 0,
1178 "Found no digits to convert in input", b, e);
1183 bool str_to_bool(StringPiece * src);
1185 } // namespace detail
1188 * String represented as a pair of pointers to char to unsigned
1189 * integrals. Assumes NO whitespace before or after.
1191 template <class Tgt>
1192 typename std::enable_if<
1193 std::is_integral<Tgt>::value && !std::is_signed<Tgt>::value
1194 && !std::is_same<typename std::remove_cv<Tgt>::type, bool>::value,
1196 to(const char * b, const char * e) {
1197 return detail::digits_to<Tgt>(b, e);
1201 * String represented as a pair of pointers to char to signed
1202 * integrals. Assumes NO whitespace before or after. Allows an
1203 * optional leading sign.
1205 template <class Tgt>
1206 typename std::enable_if<
1207 std::is_integral<Tgt>::value && std::is_signed<Tgt>::value,
1209 to(const char * b, const char * e) {
1210 FOLLY_RANGE_CHECK(b < e, "Empty input string in conversion to integral",
1211 to<std::string>("b: ", intptr_t(b), " e: ", intptr_t(e)));
1214 Tgt result = -to<typename std::make_unsigned<Tgt>::type>(b + 1, e);
1215 FOLLY_RANGE_CHECK_BEGIN_END(result <= 0, "Negative overflow.", b, e);
1218 FOLLY_RANGE_CHECK_BEGIN_END(*b == '+', "Invalid lead character", b, e);
1221 Tgt result = to<typename std::make_unsigned<Tgt>::type>(b, e);
1222 FOLLY_RANGE_CHECK_BEGIN_END(result >= 0, "Overflow", b, e);
1227 * Parsing strings to integrals. These routines differ from
1228 * to<integral>(string) in that they take a POINTER TO a StringPiece
1229 * and alter that StringPiece to reflect progress information.
1233 * StringPiece to integrals, with progress information. Alters the
1234 * StringPiece parameter to munch the already-parsed characters.
1236 template <class Tgt>
1237 typename std::enable_if<
1238 std::is_integral<Tgt>::value
1239 && !std::is_same<typename std::remove_cv<Tgt>::type, bool>::value,
1241 to(StringPiece * src) {
1243 auto b = src->data(), past = src->data() + src->size();
1245 FOLLY_RANGE_CHECK_STRINGPIECE(b < past,
1246 "No digits found in input string", *src);
1247 if (!isspace(*b)) break;
1252 // First digit is customized because we test for sign
1253 bool negative = false;
1254 /* static */ if (std::is_signed<Tgt>::value) {
1259 FOLLY_RANGE_CHECK_STRINGPIECE(*m == '+', "Invalid leading character in "
1260 "conversion to integral", *src);
1266 FOLLY_RANGE_CHECK_STRINGPIECE(m < past, "No digits found in input string",
1268 FOLLY_RANGE_CHECK_STRINGPIECE(isdigit(*m), "Non-digit character found", *src);
1269 m = detail::findFirstNonDigit<Tgt>(m + 1, past);
1272 /* static */ if (!std::is_signed<Tgt>::value) {
1273 result = detail::digits_to<typename std::make_unsigned<Tgt>::type>(b, m);
1275 auto t = detail::digits_to<typename std::make_unsigned<Tgt>::type>(b, m);
1278 FOLLY_RANGE_CHECK_STRINGPIECE(is_non_positive(result),
1279 "Negative overflow", *src);
1282 FOLLY_RANGE_CHECK_STRINGPIECE(is_non_negative(result), "Overflow", *src);
1285 src->advance(m - src->data());
1290 * StringPiece to bool, with progress information. Alters the
1291 * StringPiece parameter to munch the already-parsed characters.
1293 template <class Tgt>
1294 typename std::enable_if<
1295 std::is_same<typename std::remove_cv<Tgt>::type, bool>::value,
1297 to(StringPiece * src) {
1298 return detail::str_to_bool(src);
1304 * Enforce that the suffix following a number is made up only of whitespace.
1306 inline void enforceWhitespace(const char* b, const char* e) {
1307 for (; b != e; ++b) {
1308 FOLLY_RANGE_CHECK_BEGIN_END(isspace(*b),
1309 to<std::string>("Non-whitespace: ", *b),
1314 } // namespace detail
1317 * String or StringPiece to integrals. Accepts leading and trailing
1318 * whitespace, but no non-space trailing characters.
1320 template <class Tgt>
1321 typename std::enable_if<
1322 std::is_integral<Tgt>::value,
1324 to(StringPiece src) {
1325 Tgt result = to<Tgt>(&src);
1326 detail::enforceWhitespace(src.data(), src.data() + src.size());
1330 /*******************************************************************************
1331 * Conversions from string types to floating-point types.
1332 ******************************************************************************/
1335 * StringPiece to double, with progress information. Alters the
1336 * StringPiece parameter to munch the already-parsed characters.
1338 template <class Tgt>
1339 inline typename std::enable_if<
1340 std::is_floating_point<Tgt>::value,
1342 to(StringPiece *const src) {
1343 using namespace double_conversion;
1344 static StringToDoubleConverter
1345 conv(StringToDoubleConverter::ALLOW_TRAILING_JUNK
1346 | StringToDoubleConverter::ALLOW_LEADING_SPACES,
1348 // return this for junk input string
1349 std::numeric_limits<double>::quiet_NaN(),
1352 FOLLY_RANGE_CHECK_STRINGPIECE(!src->empty(),
1353 "No digits found in input string", *src);
1356 auto result = conv.StringToDouble(src->data(),
1357 static_cast<int>(src->size()),
1358 &length); // processed char count
1360 if (!std::isnan(result)) {
1361 src->advance(length);
1365 for (;; src->advance(1)) {
1367 throw std::range_error("Unable to convert an empty string"
1368 " to a floating point value.");
1370 if (!isspace(src->front())) {
1375 // Was that "inf[inity]"?
1376 if (src->size() >= 3 && toupper((*src)[0]) == 'I'
1377 && toupper((*src)[1]) == 'N' && toupper((*src)[2]) == 'F') {
1378 if (src->size() >= 8 &&
1379 toupper((*src)[3]) == 'I' &&
1380 toupper((*src)[4]) == 'N' &&
1381 toupper((*src)[5]) == 'I' &&
1382 toupper((*src)[6]) == 'T' &&
1383 toupper((*src)[7]) == 'Y') {
1388 return std::numeric_limits<Tgt>::infinity();
1391 // Was that "-inf[inity]"?
1392 if (src->size() >= 4 && toupper((*src)[0]) == '-'
1393 && toupper((*src)[1]) == 'I' && toupper((*src)[2]) == 'N'
1394 && toupper((*src)[3]) == 'F') {
1395 if (src->size() >= 9 &&
1396 toupper((*src)[4]) == 'I' &&
1397 toupper((*src)[5]) == 'N' &&
1398 toupper((*src)[6]) == 'I' &&
1399 toupper((*src)[7]) == 'T' &&
1400 toupper((*src)[8]) == 'Y') {
1405 return -std::numeric_limits<Tgt>::infinity();
1409 if (src->size() >= 3 && toupper((*src)[0]) == 'N'
1410 && toupper((*src)[1]) == 'A' && toupper((*src)[2]) == 'N') {
1412 return std::numeric_limits<Tgt>::quiet_NaN();
1416 if (src->size() >= 4 &&
1417 toupper((*src)[0]) == '-' &&
1418 toupper((*src)[1]) == 'N' &&
1419 toupper((*src)[2]) == 'A' &&
1420 toupper((*src)[3]) == 'N') {
1422 return -std::numeric_limits<Tgt>::quiet_NaN();
1426 throw std::range_error("Unable to convert \"" + src->toString()
1427 + "\" to a floating point value.");
1431 * Any string, const char*, or StringPiece to double.
1433 template <class Tgt>
1434 typename std::enable_if<
1435 std::is_floating_point<Tgt>::value,
1437 to(StringPiece src) {
1438 Tgt result = to<double>(&src);
1439 detail::enforceWhitespace(src.data(), src.data() + src.size());
1443 /*******************************************************************************
1444 * Integral to floating point and back
1445 ******************************************************************************/
1448 * Checked conversion from integral to flating point and back. The
1449 * result must be convertible back to the source type without loss of
1450 * precision. This seems Draconian but sometimes is what's needed, and
1451 * complements existing routines nicely. For various rounding
1452 * routines, see <math>.
1454 template <class Tgt, class Src>
1455 typename std::enable_if<
1456 (std::is_integral<Src>::value && std::is_floating_point<Tgt>::value)
1458 (std::is_floating_point<Src>::value && std::is_integral<Tgt>::value),
1460 to(const Src & value) {
1462 auto witness = static_cast<Src>(result);
1463 if (value != witness) {
1464 throw std::range_error(
1465 to<std::string>("to<>: loss of precision when converting ", value,
1466 #ifdef FOLLY_HAS_RTTI
1467 " to type ", typeid(Tgt).name()
1476 /*******************************************************************************
1477 * Enum to anything and back
1478 ******************************************************************************/
1480 #if defined(__clang__) || __GNUC_PREREQ(4, 7)
1481 // std::underlying_type became available by gcc 4.7.0
1483 template <class Tgt, class Src>
1484 typename std::enable_if<
1485 std::is_enum<Src>::value && !std::is_same<Src, Tgt>::value, Tgt>::type
1486 to(const Src & value) {
1487 return to<Tgt>(static_cast<typename std::underlying_type<Src>::type>(value));
1490 template <class Tgt, class Src>
1491 typename std::enable_if<
1492 std::is_enum<Tgt>::value && !std::is_same<Src, Tgt>::value, Tgt>::type
1493 to(const Src & value) {
1494 return static_cast<Tgt>(to<typename std::underlying_type<Tgt>::type>(value));
1499 template <class Tgt, class Src>
1500 typename std::enable_if<
1501 std::is_enum<Src>::value && !std::is_same<Src, Tgt>::value, Tgt>::type
1502 to(const Src & value) {
1503 /* static */ if (Src(-1) < 0) {
1504 /* static */ if (sizeof(Src) <= sizeof(int)) {
1505 return to<Tgt>(static_cast<int>(value));
1507 return to<Tgt>(static_cast<long>(value));
1510 /* static */ if (sizeof(Src) <= sizeof(int)) {
1511 return to<Tgt>(static_cast<unsigned int>(value));
1513 return to<Tgt>(static_cast<unsigned long>(value));
1518 template <class Tgt, class Src>
1519 typename std::enable_if<
1520 std::is_enum<Tgt>::value && !std::is_same<Src, Tgt>::value, Tgt>::type
1521 to(const Src & value) {
1522 /* static */ if (Tgt(-1) < 0) {
1523 /* static */ if (sizeof(Tgt) <= sizeof(int)) {
1524 return static_cast<Tgt>(to<int>(value));
1526 return static_cast<Tgt>(to<long>(value));
1529 /* static */ if (sizeof(Tgt) <= sizeof(int)) {
1530 return static_cast<Tgt>(to<unsigned int>(value));
1532 return static_cast<Tgt>(to<unsigned long>(value));
1537 #endif // gcc 4.7 onwards
1539 } // namespace folly
1541 // FOLLY_CONV_INTERNAL is defined by Conv.cpp. Keep the FOLLY_RANGE_CHECK
1542 // macro for use in Conv.cpp, but #undefine it everywhere else we are included,
1543 // to avoid defining this global macro name in other files that include Conv.h.
1544 #ifndef FOLLY_CONV_INTERNAL
1545 #undef FOLLY_RANGE_CHECK
1546 #undef FOLLY_RANGE_CHECK_BEGIN_END
1547 #undef FOLLY_RANGE_CHECK_STRINGPIECE
1548 #undef FOLLY_RANGE_CHECK_STRINGIZE
1549 #undef FOLLY_RANGE_CHECK_STRINGIZE2
1552 #endif /* FOLLY_BASE_CONV_H_ */