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 auto 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.
264 (UNLIKELY (v >= powersOf10[minLength]));
270 if (LIKELY(v < 10)) return result;
271 if (LIKELY(v < 100)) return result + 1;
272 if (LIKELY(v < 1000)) return result + 2;
273 if (LIKELY(v < 10000)) return result + 3;
274 // Skip ahead by 4 orders of magnitude
283 * Copies the ASCII base 10 representation of v into buffer and
284 * returns the number of bytes written. Does NOT append a \0. Assumes
285 * the buffer points to digits10(v) bytes of valid memory. Note that
286 * uint64 needs at most 20 bytes, uint32_t needs at most 10 bytes,
287 * uint16_t needs at most 5 bytes, and so on. Measurements suggest
288 * that defining a separate overload for 32-bit integers is not
291 * This primitive is unsafe because it makes the size assumption and
292 * because it does not add a terminating \0.
295 inline uint32_t uint64ToBufferUnsafe(uint64_t v, char *const buffer) {
296 auto const result = digits10(v);
297 // WARNING: using size_t or pointer arithmetic for pos slows down
298 // the loop below 20x. This is because several 32-bit ops can be
299 // done in parallel, but only fewer 64-bit ones.
300 uint32_t pos = result - 1;
302 // Keep these together so a peephole optimization "sees" them and
303 // computes them in one shot.
304 auto const q = v / 10;
305 auto const r = static_cast<uint32_t>(v % 10);
306 buffer[pos--] = '0' + r;
309 // Last digit is trivial to handle
310 buffer[pos] = static_cast<uint32_t>(v) + '0';
315 * A single char gets appended.
318 void toAppend(char value, Tgt * result) {
323 constexpr typename std::enable_if<
324 std::is_same<T, char>::value,
326 estimateSpaceNeeded(T) {
331 * Ubiquitous helper template for writing string appenders
333 template <class T> struct IsSomeString {
334 enum { value = std::is_same<T, std::string>::value
335 || std::is_same<T, fbstring>::value };
339 * Everything implicitly convertible to const char* gets appended.
341 template <class Tgt, class Src>
342 typename std::enable_if<
343 std::is_convertible<Src, const char*>::value
344 && IsSomeString<Tgt>::value>::type
345 toAppend(Src value, Tgt * result) {
346 // Treat null pointers like an empty string, as in:
347 // operator<<(std::ostream&, const char*).
348 const char* c = value;
350 result->append(value);
355 typename std::enable_if<
356 std::is_convertible<Src, const char*>::value,
358 estimateSpaceNeeded(Src value) {
359 const char *c = value;
361 return folly::StringPiece(value).size();
367 typename std::enable_if<
368 (std::is_convertible<Src, folly::StringPiece>::value ||
369 IsSomeString<Src>::value) &&
370 !std::is_convertible<Src, const char*>::value,
372 estimateSpaceNeeded(Src value) {
373 return folly::StringPiece(value).size();
377 typename std::enable_if<
378 std::is_pointer<Src>::value &&
379 IsSomeString<std::remove_pointer<Src>>::value,
381 estimateSpaceNeeded(Src value) {
382 return value->size();
386 * Strings get appended, too.
388 template <class Tgt, class Src>
389 typename std::enable_if<
390 IsSomeString<Src>::value && IsSomeString<Tgt>::value>::type
391 toAppend(const Src& value, Tgt * result) {
392 result->append(value);
396 * and StringPiece objects too
399 typename std::enable_if<
400 IsSomeString<Tgt>::value>::type
401 toAppend(StringPiece value, Tgt * result) {
402 result->append(value.data(), value.size());
406 * There's no implicit conversion from fbstring to other string types,
407 * so make a specialization.
410 typename std::enable_if<
411 IsSomeString<Tgt>::value>::type
412 toAppend(const fbstring& value, Tgt * result) {
413 result->append(value.data(), value.size());
416 #if FOLLY_HAVE_INT128_T
418 * Special handling for 128 bit integers.
423 toAppend(__int128 value, Tgt * result) {
424 typedef unsigned __int128 Usrc;
425 char buffer[detail::digitsEnough<unsigned __int128>() + 1];
429 p = detail::unsafeTelescope128(buffer, sizeof(buffer), Usrc(-value));
432 p = detail::unsafeTelescope128(buffer, sizeof(buffer), value);
435 result->append(buffer + p, buffer + sizeof(buffer));
440 toAppend(unsigned __int128 value, Tgt * result) {
441 char buffer[detail::digitsEnough<unsigned __int128>()];
444 p = detail::unsafeTelescope128(buffer, sizeof(buffer), value);
446 result->append(buffer + p, buffer + sizeof(buffer));
450 constexpr typename std::enable_if<
451 std::is_same<T, __int128>::value,
453 estimateSpaceNeeded(T) {
454 return detail::digitsEnough<__int128>();
458 constexpr typename std::enable_if<
459 std::is_same<T, unsigned __int128>::value,
461 estimateSpaceNeeded(T) {
462 return detail::digitsEnough<unsigned __int128>();
468 * int32_t and int64_t to string (by appending) go through here. The
469 * result is APPENDED to a preexisting string passed as the second
470 * parameter. This should be efficient with fbstring because fbstring
471 * incurs no dynamic allocation below 23 bytes and no number has more
472 * than 22 bytes in its textual representation (20 for digits, one for
473 * sign, one for the terminating 0).
475 template <class Tgt, class Src>
476 typename std::enable_if<
477 std::is_integral<Src>::value && std::is_signed<Src>::value &&
478 IsSomeString<Tgt>::value && sizeof(Src) >= 4>::type
479 toAppend(Src value, Tgt * result) {
482 result->push_back('-');
483 result->append(buffer, uint64ToBufferUnsafe(-uint64_t(value), buffer));
485 result->append(buffer, uint64ToBufferUnsafe(value, buffer));
490 typename std::enable_if<
491 std::is_integral<Src>::value && std::is_signed<Src>::value
492 && sizeof(Src) >= 4 && sizeof(Src) < 16,
494 estimateSpaceNeeded(Src value) {
496 return 1 + digits10(static_cast<uint64_t>(-value));
499 return digits10(static_cast<uint64_t>(value));
503 * As above, but for uint32_t and uint64_t.
505 template <class Tgt, class Src>
506 typename std::enable_if<
507 std::is_integral<Src>::value && !std::is_signed<Src>::value
508 && IsSomeString<Tgt>::value && sizeof(Src) >= 4>::type
509 toAppend(Src value, Tgt * result) {
511 result->append(buffer, buffer + uint64ToBufferUnsafe(value, buffer));
515 typename std::enable_if<
516 std::is_integral<Src>::value && !std::is_signed<Src>::value
517 && sizeof(Src) >= 4 && sizeof(Src) < 16,
519 estimateSpaceNeeded(Src value) {
520 return digits10(value);
524 * All small signed and unsigned integers to string go through 32-bit
525 * types int32_t and uint32_t, respectively.
527 template <class Tgt, class Src>
528 typename std::enable_if<
529 std::is_integral<Src>::value
530 && IsSomeString<Tgt>::value && sizeof(Src) < 4>::type
531 toAppend(Src value, Tgt * result) {
533 std::conditional<std::is_signed<Src>::value, int64_t, uint64_t>::type
535 toAppend<Tgt>(static_cast<Intermediate>(value), result);
539 typename std::enable_if<
540 std::is_integral<Src>::value
542 && !std::is_same<Src, char>::value,
544 estimateSpaceNeeded(Src value) {
546 std::conditional<std::is_signed<Src>::value, int64_t, uint64_t>::type
548 return estimateSpaceNeeded(static_cast<Intermediate>(value));
551 #if defined(__clang__) || __GNUC_PREREQ(4, 7)
552 // std::underlying_type became available by gcc 4.7.0
555 * Enumerated values get appended as integers.
557 template <class Tgt, class Src>
558 typename std::enable_if<
559 std::is_enum<Src>::value && IsSomeString<Tgt>::value>::type
560 toAppend(Src value, Tgt * result) {
562 static_cast<typename std::underlying_type<Src>::type>(value), result);
566 typename std::enable_if<
567 std::is_enum<Src>::value, size_t>::type
568 estimateSpaceNeeded(Src value) {
569 return estimateSpaceNeeded(
570 static_cast<typename std::underlying_type<Src>::type>(value));
576 * Enumerated values get appended as integers.
578 template <class Tgt, class Src>
579 typename std::enable_if<
580 std::is_enum<Src>::value && IsSomeString<Tgt>::value>::type
581 toAppend(Src value, Tgt * result) {
582 /* static */ if (Src(-1) < 0) {
583 /* static */ if (sizeof(Src) <= sizeof(int)) {
584 toAppend(static_cast<int>(value), result);
586 toAppend(static_cast<long>(value), result);
589 /* static */ if (sizeof(Src) <= sizeof(int)) {
590 toAppend(static_cast<unsigned int>(value), result);
592 toAppend(static_cast<unsigned long>(value), result);
598 typename std::enable_if<
599 std::is_enum<Src>::value, size_t>::type
600 estimateSpaceNeeded(Src value) {
601 /* static */ if (Src(-1) < 0) {
602 /* static */ if (sizeof(Src) <= sizeof(int)) {
603 return estimateSpaceNeeded(static_cast<int>(value));
605 return estimateSpaceNeeded(static_cast<long>(value));
608 /* static */ if (sizeof(Src) <= sizeof(int)) {
609 return estimateSpaceNeeded(static_cast<unsigned int>(value));
611 return estimateSpaceNeeded(static_cast<unsigned long>(value));
616 #endif // gcc 4.7 onwards
618 /*******************************************************************************
619 * Conversions from floating-point types to string types.
620 ******************************************************************************/
623 constexpr int kConvMaxDecimalInShortestLow = -6;
624 constexpr int kConvMaxDecimalInShortestHigh = 21;
627 /** Wrapper around DoubleToStringConverter **/
628 template <class Tgt, class Src>
629 typename std::enable_if<
630 std::is_floating_point<Src>::value
631 && IsSomeString<Tgt>::value>::type
635 double_conversion::DoubleToStringConverter::DtoaMode mode,
636 unsigned int numDigits) {
637 using namespace double_conversion;
638 DoubleToStringConverter
639 conv(DoubleToStringConverter::NO_FLAGS,
640 "infinity", "NaN", 'E',
641 detail::kConvMaxDecimalInShortestLow,
642 detail::kConvMaxDecimalInShortestHigh,
643 6, // max leading padding zeros
644 1); // max trailing padding zeros
646 StringBuilder builder(buffer, sizeof(buffer));
648 case DoubleToStringConverter::SHORTEST:
649 conv.ToShortest(value, &builder);
651 case DoubleToStringConverter::FIXED:
652 conv.ToFixed(value, numDigits, &builder);
655 CHECK(mode == DoubleToStringConverter::PRECISION);
656 conv.ToPrecision(value, numDigits, &builder);
659 const size_t length = builder.position();
661 result->append(buffer, length);
665 * As above, but for floating point
667 template <class Tgt, class Src>
668 typename std::enable_if<
669 std::is_floating_point<Src>::value
670 && IsSomeString<Tgt>::value>::type
671 toAppend(Src value, Tgt * result) {
673 value, result, double_conversion::DoubleToStringConverter::SHORTEST, 0);
677 * Upper bound of the length of the output from
678 * DoubleToStringConverter::ToShortest(double, StringBuilder*),
679 * as used in toAppend(double, string*).
682 typename std::enable_if<
683 std::is_floating_point<Src>::value, size_t>::type
684 estimateSpaceNeeded(Src value) {
685 // kBase10MaximalLength is 17. We add 1 for decimal point,
686 // e.g. 10.0/9 is 17 digits and 18 characters, including the decimal point.
687 constexpr int kMaxMantissaSpace =
688 double_conversion::DoubleToStringConverter::kBase10MaximalLength + 1;
689 // strlen("E-") + digits10(numeric_limits<double>::max_exponent10)
690 constexpr int kMaxExponentSpace = 2 + 3;
691 static const int kMaxPositiveSpace = std::max({
692 // E.g. 1.1111111111111111E-100.
693 kMaxMantissaSpace + kMaxExponentSpace,
694 // E.g. 0.000001.1111111111111111, if kConvMaxDecimalInShortestLow is -6.
695 kMaxMantissaSpace - detail::kConvMaxDecimalInShortestLow,
696 // If kConvMaxDecimalInShortestHigh is 21, then 1e21 is the smallest
697 // number > 1 which ToShortest outputs in exponential notation,
698 // so 21 is the longest non-exponential number > 1.
699 detail::kConvMaxDecimalInShortestHigh
701 return kMaxPositiveSpace + (value < 0); // +1 for minus sign, if negative
705 * This can be specialized, together with adding specialization
706 * for estimateSpaceNeed for your type, so that we allocate
707 * as much as you need instead of the default
710 struct HasLengthEstimator : std::false_type {};
713 constexpr typename std::enable_if<
714 !std::is_fundamental<Src>::value
715 #ifdef FOLLY_HAVE_INT128_T
716 // On OSX 10.10, is_fundamental<__int128> is false :-O
717 && !std::is_same<__int128, Src>::value
718 && !std::is_same<unsigned __int128, Src>::value
720 && !IsSomeString<Src>::value
721 && !std::is_convertible<Src, const char*>::value
722 && !std::is_convertible<Src, StringPiece>::value
723 && !std::is_enum<Src>::value
724 && !HasLengthEstimator<Src>::value,
726 estimateSpaceNeeded(const Src&) {
727 return sizeof(Src) + 1; // dumbest best effort ever?
732 inline size_t estimateSpaceToReserve(size_t sofar) {
736 template <class T, class... Ts>
737 size_t estimateSpaceToReserve(size_t sofar, const T& v, const Ts&... vs) {
738 return estimateSpaceToReserve(sofar + estimateSpaceNeeded(v), vs...);
742 size_t estimateSpaceToReserve(size_t sofar, const T& v) {
743 return sofar + estimateSpaceNeeded(v);
747 void reserveInTarget(const Ts&...vs) {
748 getLastElement(vs...)->reserve(estimateSpaceToReserve(0, vs...));
751 template<class Delimiter, class...Ts>
752 void reserveInTargetDelim(const Delimiter& d, const Ts&...vs) {
753 static_assert(sizeof...(vs) >= 2, "Needs at least 2 args");
754 size_t fordelim = (sizeof...(vs) - 2) * estimateSpaceToReserve(0, d);
755 getLastElement(vs...)->reserve(estimateSpaceToReserve(fordelim, vs...));
759 * Variadic base case: append one element
761 template <class T, class Tgt>
762 typename std::enable_if<
763 IsSomeString<typename std::remove_pointer<Tgt>::type>
765 toAppendStrImpl(const T& v, Tgt result) {
769 template <class T, class... Ts>
770 typename std::enable_if<sizeof...(Ts) >= 2
772 typename std::remove_pointer<
773 typename detail::last_element<Ts...>::type
774 >::type>::value>::type
775 toAppendStrImpl(const T& v, const Ts&... vs) {
776 toAppend(v, getLastElement(vs...));
777 toAppendStrImpl(vs...);
780 template <class Delimiter, class T, class Tgt>
781 typename std::enable_if<
782 IsSomeString<typename std::remove_pointer<Tgt>::type>
784 toAppendDelimStrImpl(const Delimiter& delim, const T& v, Tgt result) {
788 template <class Delimiter, class T, class... Ts>
789 typename std::enable_if<sizeof...(Ts) >= 2
791 typename std::remove_pointer<
792 typename detail::last_element<Ts...>::type
793 >::type>::value>::type
794 toAppendDelimStrImpl(const Delimiter& delim, const T& v, const Ts&... vs) {
795 // we are really careful here, calling toAppend with just one element does
796 // not try to estimate space needed (as we already did that). If we call
797 // toAppend(v, delim, ....) we would do unnecesary size calculation
798 toAppend(v, detail::getLastElement(vs...));
799 toAppend(delim, detail::getLastElement(vs...));
800 toAppendDelimStrImpl(delim, vs...);
806 * Variadic conversion to string. Appends each element in turn.
807 * If we have two or more things to append, we it will not reserve
808 * the space for them and will depend on strings exponential growth.
809 * If you just append once consider using toAppendFit which reserves
810 * the space needed (but does not have exponential as a result).
812 template <class... Ts>
813 typename std::enable_if<sizeof...(Ts) >= 3
815 typename std::remove_pointer<
816 typename detail::last_element<Ts...>::type
817 >::type>::value>::type
818 toAppend(const Ts&... vs) {
819 detail::toAppendStrImpl(vs...);
823 * Special version of the call that preallocates exaclty as much memory
824 * as need for arguments to be stored in target. This means we are
825 * not doing exponential growth when we append. If you are using it
826 * in a loop you are aiming at your foot with a big perf-destroying
828 * On the other hand if you are appending to a string once, this
829 * will probably save a few calls to malloc.
831 template <class... Ts>
832 typename std::enable_if<
834 typename std::remove_pointer<
835 typename detail::last_element<Ts...>::type
836 >::type>::value>::type
837 toAppendFit(const Ts&... vs) {
838 detail::reserveInTarget(vs...);
843 void toAppendFit(const Ts&) {}
846 * Variadic base case: do nothing.
849 typename std::enable_if<IsSomeString<Tgt>::value>::type
850 toAppend(Tgt* result) {
854 * Variadic base case: do nothing.
856 template <class Delimiter, class Tgt>
857 typename std::enable_if<IsSomeString<Tgt>::value>::type
858 toAppendDelim(const Delimiter& delim, Tgt* result) {
862 * 1 element: same as toAppend.
864 template <class Delimiter, class T, class Tgt>
865 typename std::enable_if<IsSomeString<Tgt>::value>::type
866 toAppendDelim(const Delimiter& delim, const T& v, Tgt* tgt) {
871 * Append to string with a delimiter in between elements. Check out
872 * comments for toAppend for details about memory allocation.
874 template <class Delimiter, class... Ts>
875 typename std::enable_if<sizeof...(Ts) >= 3
877 typename std::remove_pointer<
878 typename detail::last_element<Ts...>::type
879 >::type>::value>::type
880 toAppendDelim(const Delimiter& delim, const Ts&... vs) {
881 detail::toAppendDelimStrImpl(delim, vs...);
885 * Detail in comment for toAppendFit
887 template <class Delimiter, class... Ts>
888 typename std::enable_if<
890 typename std::remove_pointer<
891 typename detail::last_element<Ts...>::type
892 >::type>::value>::type
893 toAppendDelimFit(const Delimiter& delim, const Ts&... vs) {
894 detail::reserveInTargetDelim(delim, vs...);
895 toAppendDelim(delim, vs...);
898 template <class De, class Ts>
899 void toAppendDelimFit(const De&, const Ts&) {}
902 * to<SomeString>(v1, v2, ...) uses toAppend() (see below) as back-end
905 template <class Tgt, class... Ts>
906 typename std::enable_if<
907 IsSomeString<Tgt>::value && (
908 sizeof...(Ts) != 1 ||
909 !std::is_same<Tgt, typename detail::last_element<Ts...>::type>::value),
911 to(const Ts&... vs) {
913 toAppendFit(vs..., &result);
918 * toDelim<SomeString>(SomeString str) returns itself.
920 template <class Tgt, class Delim, class Src>
921 typename std::enable_if<
922 IsSomeString<Tgt>::value && std::is_same<Tgt, Src>::value,
924 toDelim(const Delim& delim, const Src & value) {
929 * toDelim<SomeString>(delim, v1, v2, ...) uses toAppendDelim() as
930 * back-end for all types.
932 template <class Tgt, class Delim, class... Ts>
933 typename std::enable_if<
934 IsSomeString<Tgt>::value && (
935 sizeof...(Ts) != 1 ||
936 !std::is_same<Tgt, typename detail::last_element<Ts...>::type>::value),
938 toDelim(const Delim& delim, const Ts&... vs) {
940 toAppendDelimFit(delim, vs..., &result);
944 /*******************************************************************************
945 * Conversions from string types to integral types.
946 ******************************************************************************/
951 * Finds the first non-digit in a string. The number of digits
952 * searched depends on the precision of the Tgt integral. Assumes the
953 * string starts with NO whitespace and NO sign.
955 * The semantics of the routine is:
957 * if (b >= e || !isdigit(*b)) return b;
960 * Complete unrolling marks bottom-line (i.e. entire conversion)
961 * improvements of 20%.
964 const char* findFirstNonDigit(const char* b, const char* e) {
966 auto const c = static_cast<unsigned>(*b) - '0';
972 // Maximum value of number when represented as a string
973 template <class T> struct MaxString {
974 static const char*const value;
979 * Lookup tables that converts from a decimal character value to an integral
980 * binary value, shifted by a decimal "shift" multiplier.
981 * For all character values in the range '0'..'9', the table at those
982 * index locations returns the actual decimal value shifted by the multiplier.
983 * For all other values, the lookup table returns an invalid OOR value.
985 // Out-of-range flag value, larger than the largest value that can fit in
986 // four decimal bytes (9999), but four of these added up together should
987 // still not overflow uint16_t.
988 constexpr int32_t OOR = 10000;
990 __attribute__((__aligned__(16))) constexpr uint16_t shift1[] = {
991 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 0-9
992 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 10
993 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 20
994 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 30
995 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, 0, // 40
996 1, 2, 3, 4, 5, 6, 7, 8, 9, OOR, OOR,
997 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 60
998 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 70
999 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 80
1000 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 90
1001 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 100
1002 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 110
1003 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 120
1004 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 130
1005 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 140
1006 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 150
1007 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 160
1008 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 170
1009 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 180
1010 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 190
1011 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 200
1012 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 210
1013 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 220
1014 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 230
1015 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 240
1016 OOR, OOR, OOR, OOR, OOR, OOR // 250
1019 __attribute__((__aligned__(16))) constexpr uint16_t shift10[] = {
1020 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 0-9
1021 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 10
1022 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 20
1023 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 30
1024 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, 0, // 40
1025 10, 20, 30, 40, 50, 60, 70, 80, 90, OOR, OOR,
1026 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 60
1027 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 70
1028 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 80
1029 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 90
1030 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 100
1031 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 110
1032 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 120
1033 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 130
1034 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 140
1035 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 150
1036 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 160
1037 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 170
1038 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 180
1039 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 190
1040 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 200
1041 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 210
1042 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 220
1043 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 230
1044 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 240
1045 OOR, OOR, OOR, OOR, OOR, OOR // 250
1048 __attribute__((__aligned__(16))) constexpr uint16_t shift100[] = {
1049 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 0-9
1050 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 10
1051 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 20
1052 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 30
1053 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, 0, // 40
1054 100, 200, 300, 400, 500, 600, 700, 800, 900, OOR, OOR,
1055 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 60
1056 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 70
1057 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 80
1058 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 90
1059 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 100
1060 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 110
1061 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 120
1062 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 130
1063 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 140
1064 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 150
1065 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 160
1066 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 170
1067 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 180
1068 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 190
1069 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 200
1070 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 210
1071 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 220
1072 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 230
1073 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 240
1074 OOR, OOR, OOR, OOR, OOR, OOR // 250
1077 __attribute__((__aligned__(16))) constexpr uint16_t shift1000[] = {
1078 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 0-9
1079 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 10
1080 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 20
1081 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 30
1082 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, 0, // 40
1083 1000, 2000, 3000, 4000, 5000, 6000, 7000, 8000, 9000, OOR, OOR,
1084 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 60
1085 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 70
1086 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 80
1087 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 90
1088 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 100
1089 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 110
1090 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 120
1091 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 130
1092 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 140
1093 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 150
1094 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 160
1095 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 170
1096 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 180
1097 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 190
1098 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 200
1099 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 210
1100 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 220
1101 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 230
1102 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 240
1103 OOR, OOR, OOR, OOR, OOR, OOR // 250
1107 * String represented as a pair of pointers to char to unsigned
1108 * integrals. Assumes NO whitespace before or after, and also that the
1109 * string is composed entirely of digits. Tgt must be unsigned, and no
1110 * sign is allowed in the string (even it's '+'). String may be empty,
1111 * in which case digits_to throws.
1113 template <class Tgt>
1114 Tgt digits_to(const char * b, const char * e) {
1116 static_assert(!std::is_signed<Tgt>::value, "Unsigned type expected");
1119 const size_t size = e - b;
1121 /* Although the string is entirely made of digits, we still need to
1122 * check for overflow.
1124 if (size >= std::numeric_limits<Tgt>::digits10 + 1) {
1125 // Leading zeros? If so, recurse to keep things simple
1126 if (b < e && *b == '0') {
1128 if (b == e) return 0; // just zeros, e.g. "0000"
1129 if (*b != '0') return digits_to<Tgt>(b, e);
1132 FOLLY_RANGE_CHECK_BEGIN_END(
1133 size == std::numeric_limits<Tgt>::digits10 + 1 &&
1134 strncmp(b, detail::MaxString<Tgt>::value, size) <= 0,
1135 "Numeric overflow upon conversion", b, e);
1138 // Here we know that the number won't overflow when
1139 // converted. Proceed without checks.
1143 for (; e - b >= 4; b += 4) {
1145 const int32_t r0 = shift1000[static_cast<size_t>(b[0])];
1146 const int32_t r1 = shift100[static_cast<size_t>(b[1])];
1147 const int32_t r2 = shift10[static_cast<size_t>(b[2])];
1148 const int32_t r3 = shift1[static_cast<size_t>(b[3])];
1149 const auto sum = r0 + r1 + r2 + r3;
1150 assert(sum < OOR && "Assumption: string only has digits");
1156 const int32_t r0 = shift100[static_cast<size_t>(b[0])];
1157 const int32_t r1 = shift10[static_cast<size_t>(b[1])];
1158 const int32_t r2 = shift1[static_cast<size_t>(b[2])];
1159 const auto sum = r0 + r1 + r2;
1160 assert(sum < OOR && "Assumption: string only has digits");
1161 return result * 1000 + sum;
1164 const int32_t r0 = shift10[static_cast<size_t>(b[0])];
1165 const int32_t r1 = shift1[static_cast<size_t>(b[1])];
1166 const auto sum = r0 + r1;
1167 assert(sum < OOR && "Assumption: string only has digits");
1168 return result * 100 + sum;
1171 const int32_t sum = shift1[static_cast<size_t>(b[0])];
1172 assert(sum < OOR && "Assumption: string only has digits");
1173 return result * 10 + sum;
1178 FOLLY_RANGE_CHECK_BEGIN_END(size > 0,
1179 "Found no digits to convert in input", b, e);
1184 bool str_to_bool(StringPiece * src);
1186 } // namespace detail
1189 * String represented as a pair of pointers to char to unsigned
1190 * integrals. Assumes NO whitespace before or after.
1192 template <class Tgt>
1193 typename std::enable_if<
1194 std::is_integral<Tgt>::value && !std::is_signed<Tgt>::value
1195 && !std::is_same<typename std::remove_cv<Tgt>::type, bool>::value,
1197 to(const char * b, const char * e) {
1198 return detail::digits_to<Tgt>(b, e);
1202 * String represented as a pair of pointers to char to signed
1203 * integrals. Assumes NO whitespace before or after. Allows an
1204 * optional leading sign.
1206 template <class Tgt>
1207 typename std::enable_if<
1208 std::is_integral<Tgt>::value && std::is_signed<Tgt>::value,
1210 to(const char * b, const char * e) {
1211 FOLLY_RANGE_CHECK(b < e, "Empty input string in conversion to integral",
1212 to<std::string>("b: ", intptr_t(b), " e: ", intptr_t(e)));
1215 Tgt result = -to<typename std::make_unsigned<Tgt>::type>(b + 1, e);
1216 FOLLY_RANGE_CHECK_BEGIN_END(result <= 0, "Negative overflow.", b, e);
1219 FOLLY_RANGE_CHECK_BEGIN_END(*b == '+', "Invalid lead character", b, e);
1222 Tgt result = to<typename std::make_unsigned<Tgt>::type>(b, e);
1223 FOLLY_RANGE_CHECK_BEGIN_END(result >= 0, "Overflow", b, e);
1228 * Parsing strings to integrals. These routines differ from
1229 * to<integral>(string) in that they take a POINTER TO a StringPiece
1230 * and alter that StringPiece to reflect progress information.
1234 * StringPiece to integrals, with progress information. Alters the
1235 * StringPiece parameter to munch the already-parsed characters.
1237 template <class Tgt>
1238 typename std::enable_if<
1239 std::is_integral<Tgt>::value
1240 && !std::is_same<typename std::remove_cv<Tgt>::type, bool>::value,
1242 to(StringPiece * src) {
1244 auto b = src->data(), past = src->data() + src->size();
1246 FOLLY_RANGE_CHECK_STRINGPIECE(b < past,
1247 "No digits found in input string", *src);
1248 if (!isspace(*b)) break;
1253 // First digit is customized because we test for sign
1254 bool negative = false;
1255 /* static */ if (std::is_signed<Tgt>::value) {
1260 FOLLY_RANGE_CHECK_STRINGPIECE(*m == '+', "Invalid leading character in "
1261 "conversion to integral", *src);
1267 FOLLY_RANGE_CHECK_STRINGPIECE(m < past, "No digits found in input string",
1269 FOLLY_RANGE_CHECK_STRINGPIECE(isdigit(*m), "Non-digit character found", *src);
1270 m = detail::findFirstNonDigit<Tgt>(m + 1, past);
1273 /* static */ if (!std::is_signed<Tgt>::value) {
1274 result = detail::digits_to<typename std::make_unsigned<Tgt>::type>(b, m);
1276 auto t = detail::digits_to<typename std::make_unsigned<Tgt>::type>(b, m);
1279 FOLLY_RANGE_CHECK_STRINGPIECE(is_non_positive(result),
1280 "Negative overflow", *src);
1283 FOLLY_RANGE_CHECK_STRINGPIECE(is_non_negative(result), "Overflow", *src);
1286 src->advance(m - src->data());
1291 * StringPiece to bool, with progress information. Alters the
1292 * StringPiece parameter to munch the already-parsed characters.
1294 template <class Tgt>
1295 typename std::enable_if<
1296 std::is_same<typename std::remove_cv<Tgt>::type, bool>::value,
1298 to(StringPiece * src) {
1299 return detail::str_to_bool(src);
1305 * Enforce that the suffix following a number is made up only of whitespace.
1307 inline void enforceWhitespace(const char* b, const char* e) {
1308 for (; b != e; ++b) {
1309 FOLLY_RANGE_CHECK_BEGIN_END(isspace(*b),
1310 to<std::string>("Non-whitespace: ", *b),
1315 } // namespace detail
1318 * String or StringPiece to integrals. Accepts leading and trailing
1319 * whitespace, but no non-space trailing characters.
1321 template <class Tgt>
1322 typename std::enable_if<
1323 std::is_integral<Tgt>::value,
1325 to(StringPiece src) {
1326 Tgt result = to<Tgt>(&src);
1327 detail::enforceWhitespace(src.data(), src.data() + src.size());
1331 /*******************************************************************************
1332 * Conversions from string types to floating-point types.
1333 ******************************************************************************/
1336 * StringPiece to double, with progress information. Alters the
1337 * StringPiece parameter to munch the already-parsed characters.
1339 template <class Tgt>
1340 inline typename std::enable_if<
1341 std::is_floating_point<Tgt>::value,
1343 to(StringPiece *const src) {
1344 using namespace double_conversion;
1345 static StringToDoubleConverter
1346 conv(StringToDoubleConverter::ALLOW_TRAILING_JUNK
1347 | StringToDoubleConverter::ALLOW_LEADING_SPACES,
1349 // return this for junk input string
1350 std::numeric_limits<double>::quiet_NaN(),
1353 FOLLY_RANGE_CHECK_STRINGPIECE(!src->empty(),
1354 "No digits found in input string", *src);
1357 auto result = conv.StringToDouble(src->data(),
1358 static_cast<int>(src->size()),
1359 &length); // processed char count
1361 if (!std::isnan(result)) {
1362 src->advance(length);
1366 for (;; src->advance(1)) {
1368 throw std::range_error("Unable to convert an empty string"
1369 " to a floating point value.");
1371 if (!isspace(src->front())) {
1376 // Was that "inf[inity]"?
1377 if (src->size() >= 3 && toupper((*src)[0]) == 'I'
1378 && toupper((*src)[1]) == 'N' && toupper((*src)[2]) == 'F') {
1379 if (src->size() >= 8 &&
1380 toupper((*src)[3]) == 'I' &&
1381 toupper((*src)[4]) == 'N' &&
1382 toupper((*src)[5]) == 'I' &&
1383 toupper((*src)[6]) == 'T' &&
1384 toupper((*src)[7]) == 'Y') {
1389 return std::numeric_limits<Tgt>::infinity();
1392 // Was that "-inf[inity]"?
1393 if (src->size() >= 4 && toupper((*src)[0]) == '-'
1394 && toupper((*src)[1]) == 'I' && toupper((*src)[2]) == 'N'
1395 && toupper((*src)[3]) == 'F') {
1396 if (src->size() >= 9 &&
1397 toupper((*src)[4]) == 'I' &&
1398 toupper((*src)[5]) == 'N' &&
1399 toupper((*src)[6]) == 'I' &&
1400 toupper((*src)[7]) == 'T' &&
1401 toupper((*src)[8]) == 'Y') {
1406 return -std::numeric_limits<Tgt>::infinity();
1410 if (src->size() >= 3 && toupper((*src)[0]) == 'N'
1411 && toupper((*src)[1]) == 'A' && toupper((*src)[2]) == 'N') {
1413 return std::numeric_limits<Tgt>::quiet_NaN();
1417 if (src->size() >= 4 &&
1418 toupper((*src)[0]) == '-' &&
1419 toupper((*src)[1]) == 'N' &&
1420 toupper((*src)[2]) == 'A' &&
1421 toupper((*src)[3]) == 'N') {
1423 return -std::numeric_limits<Tgt>::quiet_NaN();
1427 throw std::range_error("Unable to convert \"" + src->toString()
1428 + "\" to a floating point value.");
1432 * Any string, const char*, or StringPiece to double.
1434 template <class Tgt>
1435 typename std::enable_if<
1436 std::is_floating_point<Tgt>::value,
1438 to(StringPiece src) {
1439 Tgt result = to<double>(&src);
1440 detail::enforceWhitespace(src.data(), src.data() + src.size());
1444 /*******************************************************************************
1445 * Integral to floating point and back
1446 ******************************************************************************/
1449 * Checked conversion from integral to flating point and back. The
1450 * result must be convertible back to the source type without loss of
1451 * precision. This seems Draconian but sometimes is what's needed, and
1452 * complements existing routines nicely. For various rounding
1453 * routines, see <math>.
1455 template <class Tgt, class Src>
1456 typename std::enable_if<
1457 (std::is_integral<Src>::value && std::is_floating_point<Tgt>::value)
1459 (std::is_floating_point<Src>::value && std::is_integral<Tgt>::value),
1461 to(const Src & value) {
1463 auto witness = static_cast<Src>(result);
1464 if (value != witness) {
1465 throw std::range_error(
1466 to<std::string>("to<>: loss of precision when converting ", value,
1467 #ifdef FOLLY_HAS_RTTI
1468 " to type ", typeid(Tgt).name()
1477 /*******************************************************************************
1478 * Enum to anything and back
1479 ******************************************************************************/
1481 #if defined(__clang__) || __GNUC_PREREQ(4, 7)
1482 // std::underlying_type became available by gcc 4.7.0
1484 template <class Tgt, class Src>
1485 typename std::enable_if<
1486 std::is_enum<Src>::value && !std::is_same<Src, Tgt>::value, Tgt>::type
1487 to(const Src & value) {
1488 return to<Tgt>(static_cast<typename std::underlying_type<Src>::type>(value));
1491 template <class Tgt, class Src>
1492 typename std::enable_if<
1493 std::is_enum<Tgt>::value && !std::is_same<Src, Tgt>::value, Tgt>::type
1494 to(const Src & value) {
1495 return static_cast<Tgt>(to<typename std::underlying_type<Tgt>::type>(value));
1500 template <class Tgt, class Src>
1501 typename std::enable_if<
1502 std::is_enum<Src>::value && !std::is_same<Src, Tgt>::value, Tgt>::type
1503 to(const Src & value) {
1504 /* static */ if (Src(-1) < 0) {
1505 /* static */ if (sizeof(Src) <= sizeof(int)) {
1506 return to<Tgt>(static_cast<int>(value));
1508 return to<Tgt>(static_cast<long>(value));
1511 /* static */ if (sizeof(Src) <= sizeof(int)) {
1512 return to<Tgt>(static_cast<unsigned int>(value));
1514 return to<Tgt>(static_cast<unsigned long>(value));
1519 template <class Tgt, class Src>
1520 typename std::enable_if<
1521 std::is_enum<Tgt>::value && !std::is_same<Src, Tgt>::value, Tgt>::type
1522 to(const Src & value) {
1523 /* static */ if (Tgt(-1) < 0) {
1524 /* static */ if (sizeof(Tgt) <= sizeof(int)) {
1525 return static_cast<Tgt>(to<int>(value));
1527 return static_cast<Tgt>(to<long>(value));
1530 /* static */ if (sizeof(Tgt) <= sizeof(int)) {
1531 return static_cast<Tgt>(to<unsigned int>(value));
1533 return static_cast<Tgt>(to<unsigned long>(value));
1538 #endif // gcc 4.7 onwards
1540 } // namespace folly
1542 // FOLLY_CONV_INTERNAL is defined by Conv.cpp. Keep the FOLLY_RANGE_CHECK
1543 // macro for use in Conv.cpp, but #undefine it everywhere else we are included,
1544 // to avoid defining this global macro name in other files that include Conv.h.
1545 #ifndef FOLLY_CONV_INTERNAL
1546 #undef FOLLY_RANGE_CHECK
1547 #undef FOLLY_RANGE_CHECK_BEGIN_END
1548 #undef FOLLY_RANGE_CHECK_STRINGPIECE
1549 #undef FOLLY_RANGE_CHECK_STRINGIZE
1550 #undef FOLLY_RANGE_CHECK_STRINGIZE2
1553 #endif /* FOLLY_BASE_CONV_H_ */