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 * Unchecked conversion from integral to boolean. This is different from the
91 * other integral conversions because we use the C convention of treating any
92 * non-zero value as true, instead of range checking.
94 template <class Tgt, class Src>
95 typename std::enable_if<
96 std::is_integral<Src>::value
97 && !std::is_same<Tgt, Src>::value
98 && std::is_same<Tgt, bool>::value,
100 to(const Src & value) {
105 * Checked conversion from integral to integral. The checks are only
106 * performed when meaningful, e.g. conversion from int to long goes
109 template <class Tgt, class Src>
110 typename std::enable_if<
111 std::is_integral<Src>::value
112 && !std::is_same<Tgt, Src>::value
113 && !std::is_same<Tgt, bool>::value
114 && std::is_integral<Tgt>::value,
116 to(const Src & value) {
117 /* static */ if (std::numeric_limits<Tgt>::max()
118 < std::numeric_limits<Src>::max()) {
120 (!greater_than<Tgt, std::numeric_limits<Tgt>::max()>(value)),
122 FOLLY_RANGE_CHECK_TO_STRING(value));
124 /* static */ if (std::is_signed<Src>::value &&
125 (!std::is_signed<Tgt>::value || sizeof(Src) > sizeof(Tgt))) {
127 (!less_than<Tgt, std::numeric_limits<Tgt>::min()>(value)),
129 FOLLY_RANGE_CHECK_TO_STRING(value));
131 return static_cast<Tgt>(value);
134 /*******************************************************************************
135 * Floating point to floating point
136 ******************************************************************************/
138 template <class Tgt, class Src>
139 typename std::enable_if<
140 std::is_floating_point<Tgt>::value
141 && std::is_floating_point<Src>::value
142 && !std::is_same<Tgt, Src>::value,
144 to(const Src & value) {
145 /* static */ if (std::numeric_limits<Tgt>::max() <
146 std::numeric_limits<Src>::max()) {
147 FOLLY_RANGE_CHECK(value <= std::numeric_limits<Tgt>::max(),
149 FOLLY_RANGE_CHECK_TO_STRING(value));
150 FOLLY_RANGE_CHECK(value >= -std::numeric_limits<Tgt>::max(),
152 FOLLY_RANGE_CHECK_TO_STRING(value));
154 return boost::implicit_cast<Tgt>(value);
157 /*******************************************************************************
159 ******************************************************************************/
164 const T& getLastElement(const T & v) {
168 template <class T, class... Ts>
169 typename std::tuple_element<
171 std::tuple<T, Ts...> >::type const&
172 getLastElement(const T&, const Ts&... vs) {
173 return getLastElement(vs...);
176 // This class exists to specialize away std::tuple_element in the case where we
177 // have 0 template arguments. Without this, Clang/libc++ will blow a
178 // static_assert even if tuple_element is protected by an enable_if.
179 template <class... Ts>
180 struct last_element {
181 typedef typename std::enable_if<
183 typename std::tuple_element<
184 sizeof...(Ts) - 1, std::tuple<Ts...>
189 struct last_element<> {
193 } // namespace detail
195 /*******************************************************************************
196 * Conversions from integral types to string types.
197 ******************************************************************************/
199 #if FOLLY_HAVE_INT128_T
202 template <typename IntegerType>
203 constexpr unsigned int
205 return ceil((double(sizeof(IntegerType) * CHAR_BIT) * M_LN2) / M_LN10);
209 unsafeTelescope128(char * buffer, size_t room, unsigned __int128 x) {
210 typedef unsigned __int128 Usrc;
213 while (x >= (Usrc(1) << 64)) { // Using 128-bit division while needed
214 const auto y = x / 10;
215 const auto digit = x % 10;
217 buffer[p--] = '0' + digit;
221 uint64_t xx = x; // Moving to faster 64-bit division thereafter
224 const auto y = xx / 10ULL;
225 const auto digit = xx % 10ULL;
227 buffer[p--] = '0' + digit;
231 buffer[p] = '0' + xx;
240 * Returns the number of digits in the base 10 representation of an
241 * uint64_t. Useful for preallocating buffers and such. It's also used
242 * internally, see below. Measurements suggest that defining a
243 * separate overload for 32-bit integers is not worthwhile.
246 inline uint32_t digits10(uint64_t v) {
249 // For this arch we can get a little help from specialized CPU instructions
250 // which can count leading zeroes; 64 minus that is appx. log (base 2).
251 // Use that to approximate base-10 digits (log_10) and then adjust if needed.
253 // 10^i, defined for i 0 through 19.
254 // This is 20 * 8 == 160 bytes, which fits neatly into 5 cache lines
255 // (assuming a cache line size of 64).
256 static const uint64_t powersOf10[20] FOLLY_ALIGNED(64) = {
257 1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000,
258 10000000000, 100000000000, 1000000000000, 10000000000000, 100000000000000,
259 1000000000000000, 10000000000000000, 100000000000000000,
260 1000000000000000000, 10000000000000000000UL
263 // "count leading zeroes" operation not valid; for 0; special case this.
268 // bits is in the ballpark of log_2(v).
269 const uint8_t leadingZeroes = __builtin_clzll(v);
270 const auto bits = 63 - leadingZeroes;
272 // approximate log_10(v) == log_10(2) * bits.
273 // Integer magic below: 77/256 is appx. 0.3010 (log_10(2)).
274 // The +1 is to make this the ceiling of the log_10 estimate.
275 const uint32_t minLength = 1 + ((bits * 77) >> 8);
277 // return that log_10 lower bound, plus adjust if input >= 10^(that bound)
278 // in case there's a small error and we misjudged length.
279 return minLength + (uint32_t) (UNLIKELY (v >= powersOf10[minLength]));
285 if (LIKELY(v < 10)) return result;
286 if (LIKELY(v < 100)) return result + 1;
287 if (LIKELY(v < 1000)) return result + 2;
288 if (LIKELY(v < 10000)) return result + 3;
289 // Skip ahead by 4 orders of magnitude
298 * Copies the ASCII base 10 representation of v into buffer and
299 * returns the number of bytes written. Does NOT append a \0. Assumes
300 * the buffer points to digits10(v) bytes of valid memory. Note that
301 * uint64 needs at most 20 bytes, uint32_t needs at most 10 bytes,
302 * uint16_t needs at most 5 bytes, and so on. Measurements suggest
303 * that defining a separate overload for 32-bit integers is not
306 * This primitive is unsafe because it makes the size assumption and
307 * because it does not add a terminating \0.
310 inline uint32_t uint64ToBufferUnsafe(uint64_t v, char *const buffer) {
311 auto const result = digits10(v);
312 // WARNING: using size_t or pointer arithmetic for pos slows down
313 // the loop below 20x. This is because several 32-bit ops can be
314 // done in parallel, but only fewer 64-bit ones.
315 uint32_t pos = result - 1;
317 // Keep these together so a peephole optimization "sees" them and
318 // computes them in one shot.
319 auto const q = v / 10;
320 auto const r = static_cast<uint32_t>(v % 10);
321 buffer[pos--] = '0' + r;
324 // Last digit is trivial to handle
325 buffer[pos] = static_cast<uint32_t>(v) + '0';
330 * A single char gets appended.
333 void toAppend(char value, Tgt * result) {
338 constexpr typename std::enable_if<
339 std::is_same<T, char>::value,
341 estimateSpaceNeeded(T) {
346 * Ubiquitous helper template for writing string appenders
348 template <class T> struct IsSomeString {
349 enum { value = std::is_same<T, std::string>::value
350 || std::is_same<T, fbstring>::value };
354 * Everything implicitly convertible to const char* gets appended.
356 template <class Tgt, class Src>
357 typename std::enable_if<
358 std::is_convertible<Src, const char*>::value
359 && IsSomeString<Tgt>::value>::type
360 toAppend(Src value, Tgt * result) {
361 // Treat null pointers like an empty string, as in:
362 // operator<<(std::ostream&, const char*).
363 const char* c = value;
365 result->append(value);
370 typename std::enable_if<
371 std::is_convertible<Src, const char*>::value,
373 estimateSpaceNeeded(Src value) {
374 const char *c = value;
376 return folly::StringPiece(value).size();
382 typename std::enable_if<
383 (std::is_convertible<Src, folly::StringPiece>::value ||
384 IsSomeString<Src>::value) &&
385 !std::is_convertible<Src, const char*>::value,
387 estimateSpaceNeeded(Src value) {
388 return folly::StringPiece(value).size();
392 typename std::enable_if<
393 std::is_pointer<Src>::value &&
394 IsSomeString<std::remove_pointer<Src>>::value,
396 estimateSpaceNeeded(Src value) {
397 return value->size();
401 * Strings get appended, too.
403 template <class Tgt, class Src>
404 typename std::enable_if<
405 IsSomeString<Src>::value && IsSomeString<Tgt>::value>::type
406 toAppend(const Src& value, Tgt * result) {
407 result->append(value);
411 * and StringPiece objects too
414 typename std::enable_if<
415 IsSomeString<Tgt>::value>::type
416 toAppend(StringPiece value, Tgt * result) {
417 result->append(value.data(), value.size());
421 * There's no implicit conversion from fbstring to other string types,
422 * so make a specialization.
425 typename std::enable_if<
426 IsSomeString<Tgt>::value>::type
427 toAppend(const fbstring& value, Tgt * result) {
428 result->append(value.data(), value.size());
431 #if FOLLY_HAVE_INT128_T
433 * Special handling for 128 bit integers.
438 toAppend(__int128 value, Tgt * result) {
439 typedef unsigned __int128 Usrc;
440 char buffer[detail::digitsEnough<unsigned __int128>() + 1];
444 p = detail::unsafeTelescope128(buffer, sizeof(buffer), Usrc(-value));
447 p = detail::unsafeTelescope128(buffer, sizeof(buffer), value);
450 result->append(buffer + p, buffer + sizeof(buffer));
455 toAppend(unsigned __int128 value, Tgt * result) {
456 char buffer[detail::digitsEnough<unsigned __int128>()];
459 p = detail::unsafeTelescope128(buffer, sizeof(buffer), value);
461 result->append(buffer + p, buffer + sizeof(buffer));
465 constexpr typename std::enable_if<
466 std::is_same<T, __int128>::value,
468 estimateSpaceNeeded(T) {
469 return detail::digitsEnough<__int128>();
473 constexpr typename std::enable_if<
474 std::is_same<T, unsigned __int128>::value,
476 estimateSpaceNeeded(T) {
477 return detail::digitsEnough<unsigned __int128>();
483 * int32_t and int64_t to string (by appending) go through here. The
484 * result is APPENDED to a preexisting string passed as the second
485 * parameter. This should be efficient with fbstring because fbstring
486 * incurs no dynamic allocation below 23 bytes and no number has more
487 * than 22 bytes in its textual representation (20 for digits, one for
488 * sign, one for the terminating 0).
490 template <class Tgt, class Src>
491 typename std::enable_if<
492 std::is_integral<Src>::value && std::is_signed<Src>::value &&
493 IsSomeString<Tgt>::value && sizeof(Src) >= 4>::type
494 toAppend(Src value, Tgt * result) {
497 result->push_back('-');
498 result->append(buffer, uint64ToBufferUnsafe(-uint64_t(value), buffer));
500 result->append(buffer, uint64ToBufferUnsafe(value, buffer));
505 typename std::enable_if<
506 std::is_integral<Src>::value && std::is_signed<Src>::value
507 && sizeof(Src) >= 4 && sizeof(Src) < 16,
509 estimateSpaceNeeded(Src value) {
511 return 1 + digits10(static_cast<uint64_t>(-value));
514 return digits10(static_cast<uint64_t>(value));
518 * As above, but for uint32_t and uint64_t.
520 template <class Tgt, class Src>
521 typename std::enable_if<
522 std::is_integral<Src>::value && !std::is_signed<Src>::value
523 && IsSomeString<Tgt>::value && sizeof(Src) >= 4>::type
524 toAppend(Src value, Tgt * result) {
526 result->append(buffer, buffer + uint64ToBufferUnsafe(value, buffer));
530 typename std::enable_if<
531 std::is_integral<Src>::value && !std::is_signed<Src>::value
532 && sizeof(Src) >= 4 && sizeof(Src) < 16,
534 estimateSpaceNeeded(Src value) {
535 return digits10(value);
539 * All small signed and unsigned integers to string go through 32-bit
540 * types int32_t and uint32_t, respectively.
542 template <class Tgt, class Src>
543 typename std::enable_if<
544 std::is_integral<Src>::value
545 && IsSomeString<Tgt>::value && sizeof(Src) < 4>::type
546 toAppend(Src value, Tgt * result) {
548 std::conditional<std::is_signed<Src>::value, int64_t, uint64_t>::type
550 toAppend<Tgt>(static_cast<Intermediate>(value), result);
554 typename std::enable_if<
555 std::is_integral<Src>::value
557 && !std::is_same<Src, char>::value,
559 estimateSpaceNeeded(Src value) {
561 std::conditional<std::is_signed<Src>::value, int64_t, uint64_t>::type
563 return estimateSpaceNeeded(static_cast<Intermediate>(value));
567 * Enumerated values get appended as integers.
569 template <class Tgt, class Src>
570 typename std::enable_if<
571 std::is_enum<Src>::value && IsSomeString<Tgt>::value>::type
572 toAppend(Src value, Tgt * result) {
574 static_cast<typename std::underlying_type<Src>::type>(value), result);
578 typename std::enable_if<
579 std::is_enum<Src>::value, size_t>::type
580 estimateSpaceNeeded(Src value) {
581 return estimateSpaceNeeded(
582 static_cast<typename std::underlying_type<Src>::type>(value));
585 /*******************************************************************************
586 * Conversions from floating-point types to string types.
587 ******************************************************************************/
590 constexpr int kConvMaxDecimalInShortestLow = -6;
591 constexpr int kConvMaxDecimalInShortestHigh = 21;
594 /** Wrapper around DoubleToStringConverter **/
595 template <class Tgt, class Src>
596 typename std::enable_if<
597 std::is_floating_point<Src>::value
598 && IsSomeString<Tgt>::value>::type
602 double_conversion::DoubleToStringConverter::DtoaMode mode,
603 unsigned int numDigits) {
604 using namespace double_conversion;
605 DoubleToStringConverter
606 conv(DoubleToStringConverter::NO_FLAGS,
607 "Infinity", "NaN", 'E',
608 detail::kConvMaxDecimalInShortestLow,
609 detail::kConvMaxDecimalInShortestHigh,
610 6, // max leading padding zeros
611 1); // max trailing padding zeros
613 StringBuilder builder(buffer, sizeof(buffer));
615 case DoubleToStringConverter::SHORTEST:
616 conv.ToShortest(value, &builder);
618 case DoubleToStringConverter::FIXED:
619 conv.ToFixed(value, numDigits, &builder);
622 CHECK(mode == DoubleToStringConverter::PRECISION);
623 conv.ToPrecision(value, numDigits, &builder);
626 const size_t length = builder.position();
628 result->append(buffer, length);
632 * As above, but for floating point
634 template <class Tgt, class Src>
635 typename std::enable_if<
636 std::is_floating_point<Src>::value
637 && IsSomeString<Tgt>::value>::type
638 toAppend(Src value, Tgt * result) {
640 value, result, double_conversion::DoubleToStringConverter::SHORTEST, 0);
644 * Upper bound of the length of the output from
645 * DoubleToStringConverter::ToShortest(double, StringBuilder*),
646 * as used in toAppend(double, string*).
649 typename std::enable_if<
650 std::is_floating_point<Src>::value, size_t>::type
651 estimateSpaceNeeded(Src value) {
652 // kBase10MaximalLength is 17. We add 1 for decimal point,
653 // e.g. 10.0/9 is 17 digits and 18 characters, including the decimal point.
654 constexpr int kMaxMantissaSpace =
655 double_conversion::DoubleToStringConverter::kBase10MaximalLength + 1;
656 // strlen("E-") + digits10(numeric_limits<double>::max_exponent10)
657 constexpr int kMaxExponentSpace = 2 + 3;
658 static const int kMaxPositiveSpace = std::max({
659 // E.g. 1.1111111111111111E-100.
660 kMaxMantissaSpace + kMaxExponentSpace,
661 // E.g. 0.000001.1111111111111111, if kConvMaxDecimalInShortestLow is -6.
662 kMaxMantissaSpace - detail::kConvMaxDecimalInShortestLow,
663 // If kConvMaxDecimalInShortestHigh is 21, then 1e21 is the smallest
664 // number > 1 which ToShortest outputs in exponential notation,
665 // so 21 is the longest non-exponential number > 1.
666 detail::kConvMaxDecimalInShortestHigh
668 return kMaxPositiveSpace + (value < 0); // +1 for minus sign, if negative
672 * This can be specialized, together with adding specialization
673 * for estimateSpaceNeed for your type, so that we allocate
674 * as much as you need instead of the default
677 struct HasLengthEstimator : std::false_type {};
680 constexpr typename std::enable_if<
681 !std::is_fundamental<Src>::value
682 #ifdef FOLLY_HAVE_INT128_T
683 // On OSX 10.10, is_fundamental<__int128> is false :-O
684 && !std::is_same<__int128, Src>::value
685 && !std::is_same<unsigned __int128, Src>::value
687 && !IsSomeString<Src>::value
688 && !std::is_convertible<Src, const char*>::value
689 && !std::is_convertible<Src, StringPiece>::value
690 && !std::is_enum<Src>::value
691 && !HasLengthEstimator<Src>::value,
693 estimateSpaceNeeded(const Src&) {
694 return sizeof(Src) + 1; // dumbest best effort ever?
699 inline size_t estimateSpaceToReserve(size_t sofar) {
703 template <class T, class... Ts>
704 size_t estimateSpaceToReserve(size_t sofar, const T& v, const Ts&... vs) {
705 return estimateSpaceToReserve(sofar + estimateSpaceNeeded(v), vs...);
709 size_t estimateSpaceToReserve(size_t sofar, const T& v) {
710 return sofar + estimateSpaceNeeded(v);
714 void reserveInTarget(const Ts&...vs) {
715 getLastElement(vs...)->reserve(estimateSpaceToReserve(0, vs...));
718 template<class Delimiter, class...Ts>
719 void reserveInTargetDelim(const Delimiter& d, const Ts&...vs) {
720 static_assert(sizeof...(vs) >= 2, "Needs at least 2 args");
721 size_t fordelim = (sizeof...(vs) - 2) * estimateSpaceToReserve(0, d);
722 getLastElement(vs...)->reserve(estimateSpaceToReserve(fordelim, vs...));
726 * Variadic base case: append one element
728 template <class T, class Tgt>
729 typename std::enable_if<
730 IsSomeString<typename std::remove_pointer<Tgt>::type>
732 toAppendStrImpl(const T& v, Tgt result) {
736 template <class T, class... Ts>
737 typename std::enable_if<sizeof...(Ts) >= 2
739 typename std::remove_pointer<
740 typename detail::last_element<Ts...>::type
741 >::type>::value>::type
742 toAppendStrImpl(const T& v, const Ts&... vs) {
743 toAppend(v, getLastElement(vs...));
744 toAppendStrImpl(vs...);
747 template <class Delimiter, class T, class Tgt>
748 typename std::enable_if<
749 IsSomeString<typename std::remove_pointer<Tgt>::type>
751 toAppendDelimStrImpl(const Delimiter& delim, const T& v, Tgt result) {
755 template <class Delimiter, class T, class... Ts>
756 typename std::enable_if<sizeof...(Ts) >= 2
758 typename std::remove_pointer<
759 typename detail::last_element<Ts...>::type
760 >::type>::value>::type
761 toAppendDelimStrImpl(const Delimiter& delim, const T& v, const Ts&... vs) {
762 // we are really careful here, calling toAppend with just one element does
763 // not try to estimate space needed (as we already did that). If we call
764 // toAppend(v, delim, ....) we would do unnecesary size calculation
765 toAppend(v, detail::getLastElement(vs...));
766 toAppend(delim, detail::getLastElement(vs...));
767 toAppendDelimStrImpl(delim, vs...);
773 * Variadic conversion to string. Appends each element in turn.
774 * If we have two or more things to append, we it will not reserve
775 * the space for them and will depend on strings exponential growth.
776 * If you just append once consider using toAppendFit which reserves
777 * the space needed (but does not have exponential as a result).
779 template <class... Ts>
780 typename std::enable_if<sizeof...(Ts) >= 3
782 typename std::remove_pointer<
783 typename detail::last_element<Ts...>::type
784 >::type>::value>::type
785 toAppend(const Ts&... vs) {
786 ::folly::detail::toAppendStrImpl(vs...);
790 * Special version of the call that preallocates exaclty as much memory
791 * as need for arguments to be stored in target. This means we are
792 * not doing exponential growth when we append. If you are using it
793 * in a loop you are aiming at your foot with a big perf-destroying
795 * On the other hand if you are appending to a string once, this
796 * will probably save a few calls to malloc.
798 template <class... Ts>
799 typename std::enable_if<
801 typename std::remove_pointer<
802 typename detail::last_element<Ts...>::type
803 >::type>::value>::type
804 toAppendFit(const Ts&... vs) {
805 ::folly::detail::reserveInTarget(vs...);
810 void toAppendFit(const Ts&) {}
813 * Variadic base case: do nothing.
816 typename std::enable_if<IsSomeString<Tgt>::value>::type
817 toAppend(Tgt* result) {
821 * Variadic base case: do nothing.
823 template <class Delimiter, class Tgt>
824 typename std::enable_if<IsSomeString<Tgt>::value>::type
825 toAppendDelim(const Delimiter& delim, Tgt* result) {
829 * 1 element: same as toAppend.
831 template <class Delimiter, class T, class Tgt>
832 typename std::enable_if<IsSomeString<Tgt>::value>::type
833 toAppendDelim(const Delimiter& delim, const T& v, Tgt* tgt) {
838 * Append to string with a delimiter in between elements. Check out
839 * comments for toAppend for details about memory allocation.
841 template <class Delimiter, class... Ts>
842 typename std::enable_if<sizeof...(Ts) >= 3
844 typename std::remove_pointer<
845 typename detail::last_element<Ts...>::type
846 >::type>::value>::type
847 toAppendDelim(const Delimiter& delim, const Ts&... vs) {
848 detail::toAppendDelimStrImpl(delim, vs...);
852 * Detail in comment for toAppendFit
854 template <class Delimiter, class... Ts>
855 typename std::enable_if<
857 typename std::remove_pointer<
858 typename detail::last_element<Ts...>::type
859 >::type>::value>::type
860 toAppendDelimFit(const Delimiter& delim, const Ts&... vs) {
861 detail::reserveInTargetDelim(delim, vs...);
862 toAppendDelim(delim, vs...);
865 template <class De, class Ts>
866 void toAppendDelimFit(const De&, const Ts&) {}
869 * to<SomeString>(v1, v2, ...) uses toAppend() (see below) as back-end
872 template <class Tgt, class... Ts>
873 typename std::enable_if<
874 IsSomeString<Tgt>::value && (
875 sizeof...(Ts) != 1 ||
876 !std::is_same<Tgt, typename detail::last_element<Ts...>::type>::value),
878 to(const Ts&... vs) {
880 toAppendFit(vs..., &result);
885 * toDelim<SomeString>(SomeString str) returns itself.
887 template <class Tgt, class Delim, class Src>
888 typename std::enable_if<
889 IsSomeString<Tgt>::value && std::is_same<Tgt, Src>::value,
891 toDelim(const Delim& delim, const Src & value) {
896 * toDelim<SomeString>(delim, v1, v2, ...) uses toAppendDelim() as
897 * back-end for all types.
899 template <class Tgt, class Delim, class... Ts>
900 typename std::enable_if<
901 IsSomeString<Tgt>::value && (
902 sizeof...(Ts) != 1 ||
903 !std::is_same<Tgt, typename detail::last_element<Ts...>::type>::value),
905 toDelim(const Delim& delim, const Ts&... vs) {
907 toAppendDelimFit(delim, vs..., &result);
911 /*******************************************************************************
912 * Conversions from string types to integral types.
913 ******************************************************************************/
918 * Finds the first non-digit in a string. The number of digits
919 * searched depends on the precision of the Tgt integral. Assumes the
920 * string starts with NO whitespace and NO sign.
922 * The semantics of the routine is:
924 * if (b >= e || !isdigit(*b)) return b;
927 * Complete unrolling marks bottom-line (i.e. entire conversion)
928 * improvements of 20%.
931 const char* findFirstNonDigit(const char* b, const char* e) {
933 auto const c = static_cast<unsigned>(*b) - '0';
939 // Maximum value of number when represented as a string
940 template <class T> struct MaxString {
941 static const char*const value;
946 * Lookup tables that converts from a decimal character value to an integral
947 * binary value, shifted by a decimal "shift" multiplier.
948 * For all character values in the range '0'..'9', the table at those
949 * index locations returns the actual decimal value shifted by the multiplier.
950 * For all other values, the lookup table returns an invalid OOR value.
952 // Out-of-range flag value, larger than the largest value that can fit in
953 // four decimal bytes (9999), but four of these added up together should
954 // still not overflow uint16_t.
955 constexpr int32_t OOR = 10000;
957 FOLLY_ALIGNED(16) constexpr uint16_t shift1[] = {
958 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 0-9
959 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 10
960 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 20
961 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 30
962 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, 0, // 40
963 1, 2, 3, 4, 5, 6, 7, 8, 9, OOR, OOR,
964 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 60
965 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 70
966 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 80
967 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 90
968 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 100
969 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 110
970 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 120
971 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 130
972 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 140
973 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 150
974 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 160
975 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 170
976 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 180
977 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 190
978 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 200
979 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 210
980 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 220
981 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 230
982 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 240
983 OOR, OOR, OOR, OOR, OOR, OOR // 250
986 FOLLY_ALIGNED(16) constexpr uint16_t shift10[] = {
987 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 0-9
988 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 10
989 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 20
990 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 30
991 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, 0, // 40
992 10, 20, 30, 40, 50, 60, 70, 80, 90, OOR, OOR,
993 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 60
994 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 70
995 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 80
996 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 90
997 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 100
998 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 110
999 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 120
1000 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 130
1001 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 140
1002 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 150
1003 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 160
1004 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 170
1005 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 180
1006 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 190
1007 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 200
1008 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 210
1009 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 220
1010 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 230
1011 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 240
1012 OOR, OOR, OOR, OOR, OOR, OOR // 250
1015 FOLLY_ALIGNED(16) constexpr uint16_t shift100[] = {
1016 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 0-9
1017 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 10
1018 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 20
1019 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 30
1020 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, 0, // 40
1021 100, 200, 300, 400, 500, 600, 700, 800, 900, OOR, OOR,
1022 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 60
1023 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 70
1024 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 80
1025 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 90
1026 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 100
1027 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 110
1028 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 120
1029 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 130
1030 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 140
1031 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 150
1032 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 160
1033 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 170
1034 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 180
1035 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 190
1036 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 200
1037 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 210
1038 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 220
1039 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 230
1040 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 240
1041 OOR, OOR, OOR, OOR, OOR, OOR // 250
1044 FOLLY_ALIGNED(16) constexpr uint16_t shift1000[] = {
1045 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 0-9
1046 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 10
1047 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 20
1048 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 30
1049 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, 0, // 40
1050 1000, 2000, 3000, 4000, 5000, 6000, 7000, 8000, 9000, OOR, OOR,
1051 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 60
1052 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 70
1053 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 80
1054 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 90
1055 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 100
1056 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 110
1057 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 120
1058 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 130
1059 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 140
1060 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 150
1061 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 160
1062 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 170
1063 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 180
1064 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 190
1065 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 200
1066 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 210
1067 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 220
1068 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 230
1069 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 240
1070 OOR, OOR, OOR, OOR, OOR, OOR // 250
1074 * String represented as a pair of pointers to char to unsigned
1075 * integrals. Assumes NO whitespace before or after, and also that the
1076 * string is composed entirely of digits. Tgt must be unsigned, and no
1077 * sign is allowed in the string (even it's '+'). String may be empty,
1078 * in which case digits_to throws.
1080 template <class Tgt>
1081 Tgt digits_to(const char * b, const char * e) {
1083 static_assert(!std::is_signed<Tgt>::value, "Unsigned type expected");
1086 const size_t size = e - b;
1088 /* Although the string is entirely made of digits, we still need to
1089 * check for overflow.
1091 if (size >= std::numeric_limits<Tgt>::digits10 + 1) {
1092 // Leading zeros? If so, recurse to keep things simple
1093 if (b < e && *b == '0') {
1095 if (b == e) return 0; // just zeros, e.g. "0000"
1096 if (*b != '0') return digits_to<Tgt>(b, e);
1099 FOLLY_RANGE_CHECK_BEGIN_END(
1100 size == std::numeric_limits<Tgt>::digits10 + 1 &&
1101 strncmp(b, detail::MaxString<Tgt>::value, size) <= 0,
1102 "Numeric overflow upon conversion", b, e);
1105 // Here we know that the number won't overflow when
1106 // converted. Proceed without checks.
1110 for (; e - b >= 4; b += 4) {
1112 const int32_t r0 = shift1000[static_cast<size_t>(b[0])];
1113 const int32_t r1 = shift100[static_cast<size_t>(b[1])];
1114 const int32_t r2 = shift10[static_cast<size_t>(b[2])];
1115 const int32_t r3 = shift1[static_cast<size_t>(b[3])];
1116 const auto sum = r0 + r1 + r2 + r3;
1117 assert(sum < OOR && "Assumption: string only has digits");
1123 const int32_t r0 = shift100[static_cast<size_t>(b[0])];
1124 const int32_t r1 = shift10[static_cast<size_t>(b[1])];
1125 const int32_t r2 = shift1[static_cast<size_t>(b[2])];
1126 const auto sum = r0 + r1 + r2;
1127 assert(sum < OOR && "Assumption: string only has digits");
1128 return result * 1000 + sum;
1131 const int32_t r0 = shift10[static_cast<size_t>(b[0])];
1132 const int32_t r1 = shift1[static_cast<size_t>(b[1])];
1133 const auto sum = r0 + r1;
1134 assert(sum < OOR && "Assumption: string only has digits");
1135 return result * 100 + sum;
1138 const int32_t sum = shift1[static_cast<size_t>(b[0])];
1139 assert(sum < OOR && "Assumption: string only has digits");
1140 return result * 10 + sum;
1145 FOLLY_RANGE_CHECK_BEGIN_END(size > 0,
1146 "Found no digits to convert in input", b, e);
1151 bool str_to_bool(StringPiece * src);
1153 } // namespace detail
1156 * String represented as a pair of pointers to char to unsigned
1157 * integrals. Assumes NO whitespace before or after.
1159 template <class Tgt>
1160 typename std::enable_if<
1161 std::is_integral<Tgt>::value && !std::is_signed<Tgt>::value
1162 && !std::is_same<typename std::remove_cv<Tgt>::type, bool>::value,
1164 to(const char * b, const char * e) {
1165 return detail::digits_to<Tgt>(b, e);
1169 * String represented as a pair of pointers to char to signed
1170 * integrals. Assumes NO whitespace before or after. Allows an
1171 * optional leading sign.
1173 template <class Tgt>
1174 typename std::enable_if<
1175 std::is_integral<Tgt>::value && std::is_signed<Tgt>::value,
1177 to(const char * b, const char * e) {
1178 FOLLY_RANGE_CHECK(b < e, "Empty input string in conversion to integral",
1179 to<std::string>("b: ", intptr_t(b), " e: ", intptr_t(e)));
1182 Tgt result = -to<typename std::make_unsigned<Tgt>::type>(b + 1, e);
1183 FOLLY_RANGE_CHECK_BEGIN_END(result <= 0, "Negative overflow.", b, e);
1186 FOLLY_RANGE_CHECK_BEGIN_END(*b == '+', "Invalid lead character", b, e);
1189 Tgt result = to<typename std::make_unsigned<Tgt>::type>(b, e);
1190 FOLLY_RANGE_CHECK_BEGIN_END(result >= 0, "Overflow", b, e);
1195 * Parsing strings to integrals. These routines differ from
1196 * to<integral>(string) in that they take a POINTER TO a StringPiece
1197 * and alter that StringPiece to reflect progress information.
1201 * StringPiece to integrals, with progress information. Alters the
1202 * StringPiece parameter to munch the already-parsed characters.
1204 template <class Tgt>
1205 typename std::enable_if<
1206 std::is_integral<Tgt>::value
1207 && !std::is_same<typename std::remove_cv<Tgt>::type, bool>::value,
1209 to(StringPiece * src) {
1211 auto b = src->data(), past = src->data() + src->size();
1213 FOLLY_RANGE_CHECK_STRINGPIECE(b < past,
1214 "No digits found in input string", *src);
1215 if (!isspace(*b)) break;
1220 // First digit is customized because we test for sign
1221 bool negative = false;
1222 /* static */ if (std::is_signed<Tgt>::value) {
1227 FOLLY_RANGE_CHECK_STRINGPIECE(*m == '+', "Invalid leading character in "
1228 "conversion to integral", *src);
1234 FOLLY_RANGE_CHECK_STRINGPIECE(m < past, "No digits found in input string",
1236 FOLLY_RANGE_CHECK_STRINGPIECE(isdigit(*m), "Non-digit character found", *src);
1237 m = detail::findFirstNonDigit<Tgt>(m + 1, past);
1240 /* static */ if (!std::is_signed<Tgt>::value) {
1241 result = detail::digits_to<typename std::make_unsigned<Tgt>::type>(b, m);
1243 auto t = detail::digits_to<typename std::make_unsigned<Tgt>::type>(b, m);
1246 FOLLY_RANGE_CHECK_STRINGPIECE(is_non_positive(result),
1247 "Negative overflow", *src);
1250 FOLLY_RANGE_CHECK_STRINGPIECE(is_non_negative(result), "Overflow", *src);
1253 src->advance(m - src->data());
1258 * StringPiece to bool, with progress information. Alters the
1259 * StringPiece parameter to munch the already-parsed characters.
1261 template <class Tgt>
1262 typename std::enable_if<
1263 std::is_same<typename std::remove_cv<Tgt>::type, bool>::value,
1265 to(StringPiece * src) {
1266 return detail::str_to_bool(src);
1272 * Enforce that the suffix following a number is made up only of whitespace.
1274 inline void enforceWhitespace(const char* b, const char* e) {
1275 for (; b != e; ++b) {
1276 FOLLY_RANGE_CHECK_BEGIN_END(isspace(*b),
1277 to<std::string>("Non-whitespace: ", *b),
1282 } // namespace detail
1285 * String or StringPiece to integrals. Accepts leading and trailing
1286 * whitespace, but no non-space trailing characters.
1288 template <class Tgt>
1289 typename std::enable_if<
1290 std::is_integral<Tgt>::value,
1292 to(StringPiece src) {
1293 Tgt result = to<Tgt>(&src);
1294 detail::enforceWhitespace(src.data(), src.data() + src.size());
1298 /*******************************************************************************
1299 * Conversions from string types to floating-point types.
1300 ******************************************************************************/
1303 * StringPiece to double, with progress information. Alters the
1304 * StringPiece parameter to munch the already-parsed characters.
1306 template <class Tgt>
1307 inline typename std::enable_if<
1308 std::is_floating_point<Tgt>::value,
1310 to(StringPiece *const src) {
1311 using namespace double_conversion;
1312 static StringToDoubleConverter
1313 conv(StringToDoubleConverter::ALLOW_TRAILING_JUNK
1314 | StringToDoubleConverter::ALLOW_LEADING_SPACES,
1316 // return this for junk input string
1317 std::numeric_limits<double>::quiet_NaN(),
1320 FOLLY_RANGE_CHECK_STRINGPIECE(!src->empty(),
1321 "No digits found in input string", *src);
1324 auto result = conv.StringToDouble(src->data(),
1325 static_cast<int>(src->size()),
1326 &length); // processed char count
1328 if (!std::isnan(result)) {
1329 src->advance(length);
1333 for (;; src->advance(1)) {
1335 throw std::range_error("Unable to convert an empty string"
1336 " to a floating point value.");
1338 if (!isspace(src->front())) {
1343 // Was that "inf[inity]"?
1344 if (src->size() >= 3 && toupper((*src)[0]) == 'I'
1345 && toupper((*src)[1]) == 'N' && toupper((*src)[2]) == 'F') {
1346 if (src->size() >= 8 &&
1347 toupper((*src)[3]) == 'I' &&
1348 toupper((*src)[4]) == 'N' &&
1349 toupper((*src)[5]) == 'I' &&
1350 toupper((*src)[6]) == 'T' &&
1351 toupper((*src)[7]) == 'Y') {
1356 return std::numeric_limits<Tgt>::infinity();
1359 // Was that "-inf[inity]"?
1360 if (src->size() >= 4 && toupper((*src)[0]) == '-'
1361 && toupper((*src)[1]) == 'I' && toupper((*src)[2]) == 'N'
1362 && toupper((*src)[3]) == 'F') {
1363 if (src->size() >= 9 &&
1364 toupper((*src)[4]) == 'I' &&
1365 toupper((*src)[5]) == 'N' &&
1366 toupper((*src)[6]) == 'I' &&
1367 toupper((*src)[7]) == 'T' &&
1368 toupper((*src)[8]) == 'Y') {
1373 return -std::numeric_limits<Tgt>::infinity();
1377 if (src->size() >= 3 && toupper((*src)[0]) == 'N'
1378 && toupper((*src)[1]) == 'A' && toupper((*src)[2]) == 'N') {
1380 return std::numeric_limits<Tgt>::quiet_NaN();
1384 if (src->size() >= 4 &&
1385 toupper((*src)[0]) == '-' &&
1386 toupper((*src)[1]) == 'N' &&
1387 toupper((*src)[2]) == 'A' &&
1388 toupper((*src)[3]) == 'N') {
1390 return -std::numeric_limits<Tgt>::quiet_NaN();
1394 throw std::range_error("Unable to convert \"" + src->toString()
1395 + "\" to a floating point value.");
1399 * Any string, const char*, or StringPiece to double.
1401 template <class Tgt>
1402 typename std::enable_if<
1403 std::is_floating_point<Tgt>::value,
1405 to(StringPiece src) {
1406 Tgt result = to<double>(&src);
1407 detail::enforceWhitespace(src.data(), src.data() + src.size());
1411 /*******************************************************************************
1412 * Integral to floating point and back
1413 ******************************************************************************/
1416 * Checked conversion from integral to flating point and back. The
1417 * result must be convertible back to the source type without loss of
1418 * precision. This seems Draconian but sometimes is what's needed, and
1419 * complements existing routines nicely. For various rounding
1420 * routines, see <math>.
1422 template <class Tgt, class Src>
1423 typename std::enable_if<
1424 (std::is_integral<Src>::value && std::is_floating_point<Tgt>::value)
1426 (std::is_floating_point<Src>::value && std::is_integral<Tgt>::value),
1428 to(const Src & value) {
1430 auto witness = static_cast<Src>(result);
1431 if (value != witness) {
1432 throw std::range_error(
1433 to<std::string>("to<>: loss of precision when converting ", value,
1434 #ifdef FOLLY_HAS_RTTI
1435 " to type ", typeid(Tgt).name()
1444 /*******************************************************************************
1445 * Enum to anything and back
1446 ******************************************************************************/
1448 template <class Tgt, class Src>
1449 typename std::enable_if<
1450 std::is_enum<Src>::value && !std::is_same<Src, Tgt>::value, Tgt>::type
1451 to(const Src & value) {
1452 return to<Tgt>(static_cast<typename std::underlying_type<Src>::type>(value));
1455 template <class Tgt, class Src>
1456 typename std::enable_if<
1457 std::is_enum<Tgt>::value && !std::is_same<Src, Tgt>::value, Tgt>::type
1458 to(const Src & value) {
1459 return static_cast<Tgt>(to<typename std::underlying_type<Tgt>::type>(value));
1462 } // namespace folly
1464 // FOLLY_CONV_INTERNAL is defined by Conv.cpp. Keep the FOLLY_RANGE_CHECK
1465 // macro for use in Conv.cpp, but #undefine it everywhere else we are included,
1466 // to avoid defining this global macro name in other files that include Conv.h.
1467 #ifndef FOLLY_CONV_INTERNAL
1468 #undef FOLLY_RANGE_CHECK
1469 #undef FOLLY_RANGE_CHECK_BEGIN_END
1470 #undef FOLLY_RANGE_CHECK_STRINGPIECE
1471 #undef FOLLY_RANGE_CHECK_STRINGIZE
1472 #undef FOLLY_RANGE_CHECK_STRINGIZE2
1475 #endif /* FOLLY_BASE_CONV_H_ */