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&, 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] FOLLY_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));
551 * Enumerated values get appended as integers.
553 template <class Tgt, class Src>
554 typename std::enable_if<
555 std::is_enum<Src>::value && IsSomeString<Tgt>::value>::type
556 toAppend(Src value, Tgt * result) {
558 static_cast<typename std::underlying_type<Src>::type>(value), result);
562 typename std::enable_if<
563 std::is_enum<Src>::value, size_t>::type
564 estimateSpaceNeeded(Src value) {
565 return estimateSpaceNeeded(
566 static_cast<typename std::underlying_type<Src>::type>(value));
569 /*******************************************************************************
570 * Conversions from floating-point types to string types.
571 ******************************************************************************/
574 constexpr int kConvMaxDecimalInShortestLow = -6;
575 constexpr int kConvMaxDecimalInShortestHigh = 21;
578 /** Wrapper around DoubleToStringConverter **/
579 template <class Tgt, class Src>
580 typename std::enable_if<
581 std::is_floating_point<Src>::value
582 && IsSomeString<Tgt>::value>::type
586 double_conversion::DoubleToStringConverter::DtoaMode mode,
587 unsigned int numDigits) {
588 using namespace double_conversion;
589 DoubleToStringConverter
590 conv(DoubleToStringConverter::NO_FLAGS,
591 "Infinity", "NaN", 'E',
592 detail::kConvMaxDecimalInShortestLow,
593 detail::kConvMaxDecimalInShortestHigh,
594 6, // max leading padding zeros
595 1); // max trailing padding zeros
597 StringBuilder builder(buffer, sizeof(buffer));
599 case DoubleToStringConverter::SHORTEST:
600 conv.ToShortest(value, &builder);
602 case DoubleToStringConverter::FIXED:
603 conv.ToFixed(value, numDigits, &builder);
606 CHECK(mode == DoubleToStringConverter::PRECISION);
607 conv.ToPrecision(value, numDigits, &builder);
610 const size_t length = builder.position();
612 result->append(buffer, length);
616 * As above, but for floating point
618 template <class Tgt, class Src>
619 typename std::enable_if<
620 std::is_floating_point<Src>::value
621 && IsSomeString<Tgt>::value>::type
622 toAppend(Src value, Tgt * result) {
624 value, result, double_conversion::DoubleToStringConverter::SHORTEST, 0);
628 * Upper bound of the length of the output from
629 * DoubleToStringConverter::ToShortest(double, StringBuilder*),
630 * as used in toAppend(double, string*).
633 typename std::enable_if<
634 std::is_floating_point<Src>::value, size_t>::type
635 estimateSpaceNeeded(Src value) {
636 // kBase10MaximalLength is 17. We add 1 for decimal point,
637 // e.g. 10.0/9 is 17 digits and 18 characters, including the decimal point.
638 constexpr int kMaxMantissaSpace =
639 double_conversion::DoubleToStringConverter::kBase10MaximalLength + 1;
640 // strlen("E-") + digits10(numeric_limits<double>::max_exponent10)
641 constexpr int kMaxExponentSpace = 2 + 3;
642 static const int kMaxPositiveSpace = std::max({
643 // E.g. 1.1111111111111111E-100.
644 kMaxMantissaSpace + kMaxExponentSpace,
645 // E.g. 0.000001.1111111111111111, if kConvMaxDecimalInShortestLow is -6.
646 kMaxMantissaSpace - detail::kConvMaxDecimalInShortestLow,
647 // If kConvMaxDecimalInShortestHigh is 21, then 1e21 is the smallest
648 // number > 1 which ToShortest outputs in exponential notation,
649 // so 21 is the longest non-exponential number > 1.
650 detail::kConvMaxDecimalInShortestHigh
652 return kMaxPositiveSpace + (value < 0); // +1 for minus sign, if negative
656 * This can be specialized, together with adding specialization
657 * for estimateSpaceNeed for your type, so that we allocate
658 * as much as you need instead of the default
661 struct HasLengthEstimator : std::false_type {};
664 constexpr typename std::enable_if<
665 !std::is_fundamental<Src>::value
666 #ifdef FOLLY_HAVE_INT128_T
667 // On OSX 10.10, is_fundamental<__int128> is false :-O
668 && !std::is_same<__int128, Src>::value
669 && !std::is_same<unsigned __int128, Src>::value
671 && !IsSomeString<Src>::value
672 && !std::is_convertible<Src, const char*>::value
673 && !std::is_convertible<Src, StringPiece>::value
674 && !std::is_enum<Src>::value
675 && !HasLengthEstimator<Src>::value,
677 estimateSpaceNeeded(const Src&) {
678 return sizeof(Src) + 1; // dumbest best effort ever?
683 inline size_t estimateSpaceToReserve(size_t sofar) {
687 template <class T, class... Ts>
688 size_t estimateSpaceToReserve(size_t sofar, const T& v, const Ts&... vs) {
689 return estimateSpaceToReserve(sofar + estimateSpaceNeeded(v), vs...);
693 size_t estimateSpaceToReserve(size_t sofar, const T& v) {
694 return sofar + estimateSpaceNeeded(v);
698 void reserveInTarget(const Ts&...vs) {
699 getLastElement(vs...)->reserve(estimateSpaceToReserve(0, vs...));
702 template<class Delimiter, class...Ts>
703 void reserveInTargetDelim(const Delimiter& d, const Ts&...vs) {
704 static_assert(sizeof...(vs) >= 2, "Needs at least 2 args");
705 size_t fordelim = (sizeof...(vs) - 2) * estimateSpaceToReserve(0, d);
706 getLastElement(vs...)->reserve(estimateSpaceToReserve(fordelim, vs...));
710 * Variadic base case: append one element
712 template <class T, class Tgt>
713 typename std::enable_if<
714 IsSomeString<typename std::remove_pointer<Tgt>::type>
716 toAppendStrImpl(const T& v, Tgt result) {
720 template <class T, class... Ts>
721 typename std::enable_if<sizeof...(Ts) >= 2
723 typename std::remove_pointer<
724 typename detail::last_element<Ts...>::type
725 >::type>::value>::type
726 toAppendStrImpl(const T& v, const Ts&... vs) {
727 toAppend(v, getLastElement(vs...));
728 toAppendStrImpl(vs...);
731 template <class Delimiter, class T, class Tgt>
732 typename std::enable_if<
733 IsSomeString<typename std::remove_pointer<Tgt>::type>
735 toAppendDelimStrImpl(const Delimiter& delim, const T& v, Tgt result) {
739 template <class Delimiter, class T, class... Ts>
740 typename std::enable_if<sizeof...(Ts) >= 2
742 typename std::remove_pointer<
743 typename detail::last_element<Ts...>::type
744 >::type>::value>::type
745 toAppendDelimStrImpl(const Delimiter& delim, const T& v, const Ts&... vs) {
746 // we are really careful here, calling toAppend with just one element does
747 // not try to estimate space needed (as we already did that). If we call
748 // toAppend(v, delim, ....) we would do unnecesary size calculation
749 toAppend(v, detail::getLastElement(vs...));
750 toAppend(delim, detail::getLastElement(vs...));
751 toAppendDelimStrImpl(delim, vs...);
757 * Variadic conversion to string. Appends each element in turn.
758 * If we have two or more things to append, we it will not reserve
759 * the space for them and will depend on strings exponential growth.
760 * If you just append once consider using toAppendFit which reserves
761 * the space needed (but does not have exponential as a result).
763 template <class... Ts>
764 typename std::enable_if<sizeof...(Ts) >= 3
766 typename std::remove_pointer<
767 typename detail::last_element<Ts...>::type
768 >::type>::value>::type
769 toAppend(const Ts&... vs) {
770 ::folly::detail::toAppendStrImpl(vs...);
774 * Special version of the call that preallocates exaclty as much memory
775 * as need for arguments to be stored in target. This means we are
776 * not doing exponential growth when we append. If you are using it
777 * in a loop you are aiming at your foot with a big perf-destroying
779 * On the other hand if you are appending to a string once, this
780 * will probably save a few calls to malloc.
782 template <class... Ts>
783 typename std::enable_if<
785 typename std::remove_pointer<
786 typename detail::last_element<Ts...>::type
787 >::type>::value>::type
788 toAppendFit(const Ts&... vs) {
789 ::folly::detail::reserveInTarget(vs...);
794 void toAppendFit(const Ts&) {}
797 * Variadic base case: do nothing.
800 typename std::enable_if<IsSomeString<Tgt>::value>::type
801 toAppend(Tgt* result) {
805 * Variadic base case: do nothing.
807 template <class Delimiter, class Tgt>
808 typename std::enable_if<IsSomeString<Tgt>::value>::type
809 toAppendDelim(const Delimiter& delim, Tgt* result) {
813 * 1 element: same as toAppend.
815 template <class Delimiter, class T, class Tgt>
816 typename std::enable_if<IsSomeString<Tgt>::value>::type
817 toAppendDelim(const Delimiter& delim, const T& v, Tgt* tgt) {
822 * Append to string with a delimiter in between elements. Check out
823 * comments for toAppend for details about memory allocation.
825 template <class Delimiter, class... Ts>
826 typename std::enable_if<sizeof...(Ts) >= 3
828 typename std::remove_pointer<
829 typename detail::last_element<Ts...>::type
830 >::type>::value>::type
831 toAppendDelim(const Delimiter& delim, const Ts&... vs) {
832 detail::toAppendDelimStrImpl(delim, vs...);
836 * Detail in comment for toAppendFit
838 template <class Delimiter, class... Ts>
839 typename std::enable_if<
841 typename std::remove_pointer<
842 typename detail::last_element<Ts...>::type
843 >::type>::value>::type
844 toAppendDelimFit(const Delimiter& delim, const Ts&... vs) {
845 detail::reserveInTargetDelim(delim, vs...);
846 toAppendDelim(delim, vs...);
849 template <class De, class Ts>
850 void toAppendDelimFit(const De&, const Ts&) {}
853 * to<SomeString>(v1, v2, ...) uses toAppend() (see below) as back-end
856 template <class Tgt, class... Ts>
857 typename std::enable_if<
858 IsSomeString<Tgt>::value && (
859 sizeof...(Ts) != 1 ||
860 !std::is_same<Tgt, typename detail::last_element<Ts...>::type>::value),
862 to(const Ts&... vs) {
864 toAppendFit(vs..., &result);
869 * toDelim<SomeString>(SomeString str) returns itself.
871 template <class Tgt, class Delim, class Src>
872 typename std::enable_if<
873 IsSomeString<Tgt>::value && std::is_same<Tgt, Src>::value,
875 toDelim(const Delim& delim, const Src & value) {
880 * toDelim<SomeString>(delim, v1, v2, ...) uses toAppendDelim() as
881 * back-end for all types.
883 template <class Tgt, class Delim, class... Ts>
884 typename std::enable_if<
885 IsSomeString<Tgt>::value && (
886 sizeof...(Ts) != 1 ||
887 !std::is_same<Tgt, typename detail::last_element<Ts...>::type>::value),
889 toDelim(const Delim& delim, const Ts&... vs) {
891 toAppendDelimFit(delim, vs..., &result);
895 /*******************************************************************************
896 * Conversions from string types to integral types.
897 ******************************************************************************/
902 * Finds the first non-digit in a string. The number of digits
903 * searched depends on the precision of the Tgt integral. Assumes the
904 * string starts with NO whitespace and NO sign.
906 * The semantics of the routine is:
908 * if (b >= e || !isdigit(*b)) return b;
911 * Complete unrolling marks bottom-line (i.e. entire conversion)
912 * improvements of 20%.
915 const char* findFirstNonDigit(const char* b, const char* e) {
917 auto const c = static_cast<unsigned>(*b) - '0';
923 // Maximum value of number when represented as a string
924 template <class T> struct MaxString {
925 static const char*const value;
930 * Lookup tables that converts from a decimal character value to an integral
931 * binary value, shifted by a decimal "shift" multiplier.
932 * For all character values in the range '0'..'9', the table at those
933 * index locations returns the actual decimal value shifted by the multiplier.
934 * For all other values, the lookup table returns an invalid OOR value.
936 // Out-of-range flag value, larger than the largest value that can fit in
937 // four decimal bytes (9999), but four of these added up together should
938 // still not overflow uint16_t.
939 constexpr int32_t OOR = 10000;
941 FOLLY_ALIGNED(16) constexpr uint16_t shift1[] = {
942 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 0-9
943 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 10
944 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 20
945 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 30
946 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, 0, // 40
947 1, 2, 3, 4, 5, 6, 7, 8, 9, OOR, OOR,
948 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 60
949 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 70
950 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 80
951 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 90
952 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 100
953 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 110
954 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 120
955 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 130
956 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 140
957 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 150
958 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 160
959 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 170
960 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 180
961 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 190
962 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 200
963 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 210
964 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 220
965 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 230
966 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 240
967 OOR, OOR, OOR, OOR, OOR, OOR // 250
970 FOLLY_ALIGNED(16) constexpr uint16_t shift10[] = {
971 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 0-9
972 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 10
973 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 20
974 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 30
975 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, 0, // 40
976 10, 20, 30, 40, 50, 60, 70, 80, 90, OOR, OOR,
977 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 60
978 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 70
979 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 80
980 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 90
981 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 100
982 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 110
983 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 120
984 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 130
985 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 140
986 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 150
987 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 160
988 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 170
989 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 180
990 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 190
991 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 200
992 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 210
993 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 220
994 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 230
995 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 240
996 OOR, OOR, OOR, OOR, OOR, OOR // 250
999 FOLLY_ALIGNED(16) constexpr uint16_t shift100[] = {
1000 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 0-9
1001 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 10
1002 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 20
1003 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 30
1004 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, 0, // 40
1005 100, 200, 300, 400, 500, 600, 700, 800, 900, OOR, OOR,
1006 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 60
1007 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 70
1008 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 80
1009 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 90
1010 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 100
1011 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 110
1012 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 120
1013 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 130
1014 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 140
1015 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 150
1016 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 160
1017 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 170
1018 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 180
1019 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 190
1020 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 200
1021 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 210
1022 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 220
1023 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 230
1024 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 240
1025 OOR, OOR, OOR, OOR, OOR, OOR // 250
1028 FOLLY_ALIGNED(16) constexpr uint16_t shift1000[] = {
1029 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 0-9
1030 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 10
1031 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 20
1032 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 30
1033 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, 0, // 40
1034 1000, 2000, 3000, 4000, 5000, 6000, 7000, 8000, 9000, OOR, OOR,
1035 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 60
1036 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 70
1037 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 80
1038 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 90
1039 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 100
1040 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 110
1041 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 120
1042 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 130
1043 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 140
1044 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 150
1045 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 160
1046 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 170
1047 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 180
1048 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 190
1049 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 200
1050 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 210
1051 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 220
1052 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 230
1053 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 240
1054 OOR, OOR, OOR, OOR, OOR, OOR // 250
1058 * String represented as a pair of pointers to char to unsigned
1059 * integrals. Assumes NO whitespace before or after, and also that the
1060 * string is composed entirely of digits. Tgt must be unsigned, and no
1061 * sign is allowed in the string (even it's '+'). String may be empty,
1062 * in which case digits_to throws.
1064 template <class Tgt>
1065 Tgt digits_to(const char * b, const char * e) {
1067 static_assert(!std::is_signed<Tgt>::value, "Unsigned type expected");
1070 const size_t size = e - b;
1072 /* Although the string is entirely made of digits, we still need to
1073 * check for overflow.
1075 if (size >= std::numeric_limits<Tgt>::digits10 + 1) {
1076 // Leading zeros? If so, recurse to keep things simple
1077 if (b < e && *b == '0') {
1079 if (b == e) return 0; // just zeros, e.g. "0000"
1080 if (*b != '0') return digits_to<Tgt>(b, e);
1083 FOLLY_RANGE_CHECK_BEGIN_END(
1084 size == std::numeric_limits<Tgt>::digits10 + 1 &&
1085 strncmp(b, detail::MaxString<Tgt>::value, size) <= 0,
1086 "Numeric overflow upon conversion", b, e);
1089 // Here we know that the number won't overflow when
1090 // converted. Proceed without checks.
1094 for (; e - b >= 4; b += 4) {
1096 const int32_t r0 = shift1000[static_cast<size_t>(b[0])];
1097 const int32_t r1 = shift100[static_cast<size_t>(b[1])];
1098 const int32_t r2 = shift10[static_cast<size_t>(b[2])];
1099 const int32_t r3 = shift1[static_cast<size_t>(b[3])];
1100 const auto sum = r0 + r1 + r2 + r3;
1101 assert(sum < OOR && "Assumption: string only has digits");
1107 const int32_t r0 = shift100[static_cast<size_t>(b[0])];
1108 const int32_t r1 = shift10[static_cast<size_t>(b[1])];
1109 const int32_t r2 = shift1[static_cast<size_t>(b[2])];
1110 const auto sum = r0 + r1 + r2;
1111 assert(sum < OOR && "Assumption: string only has digits");
1112 return result * 1000 + sum;
1115 const int32_t r0 = shift10[static_cast<size_t>(b[0])];
1116 const int32_t r1 = shift1[static_cast<size_t>(b[1])];
1117 const auto sum = r0 + r1;
1118 assert(sum < OOR && "Assumption: string only has digits");
1119 return result * 100 + sum;
1122 const int32_t sum = shift1[static_cast<size_t>(b[0])];
1123 assert(sum < OOR && "Assumption: string only has digits");
1124 return result * 10 + sum;
1129 FOLLY_RANGE_CHECK_BEGIN_END(size > 0,
1130 "Found no digits to convert in input", b, e);
1135 bool str_to_bool(StringPiece * src);
1137 } // namespace detail
1140 * String represented as a pair of pointers to char to unsigned
1141 * integrals. Assumes NO whitespace before or after.
1143 template <class Tgt>
1144 typename std::enable_if<
1145 std::is_integral<Tgt>::value && !std::is_signed<Tgt>::value
1146 && !std::is_same<typename std::remove_cv<Tgt>::type, bool>::value,
1148 to(const char * b, const char * e) {
1149 return detail::digits_to<Tgt>(b, e);
1153 * String represented as a pair of pointers to char to signed
1154 * integrals. Assumes NO whitespace before or after. Allows an
1155 * optional leading sign.
1157 template <class Tgt>
1158 typename std::enable_if<
1159 std::is_integral<Tgt>::value && std::is_signed<Tgt>::value,
1161 to(const char * b, const char * e) {
1162 FOLLY_RANGE_CHECK(b < e, "Empty input string in conversion to integral",
1163 to<std::string>("b: ", intptr_t(b), " e: ", intptr_t(e)));
1166 Tgt result = -to<typename std::make_unsigned<Tgt>::type>(b + 1, e);
1167 FOLLY_RANGE_CHECK_BEGIN_END(result <= 0, "Negative overflow.", b, e);
1170 FOLLY_RANGE_CHECK_BEGIN_END(*b == '+', "Invalid lead character", b, e);
1173 Tgt result = to<typename std::make_unsigned<Tgt>::type>(b, e);
1174 FOLLY_RANGE_CHECK_BEGIN_END(result >= 0, "Overflow", b, e);
1179 * Parsing strings to integrals. These routines differ from
1180 * to<integral>(string) in that they take a POINTER TO a StringPiece
1181 * and alter that StringPiece to reflect progress information.
1185 * StringPiece to integrals, with progress information. Alters the
1186 * StringPiece parameter to munch the already-parsed characters.
1188 template <class Tgt>
1189 typename std::enable_if<
1190 std::is_integral<Tgt>::value
1191 && !std::is_same<typename std::remove_cv<Tgt>::type, bool>::value,
1193 to(StringPiece * src) {
1195 auto b = src->data(), past = src->data() + src->size();
1197 FOLLY_RANGE_CHECK_STRINGPIECE(b < past,
1198 "No digits found in input string", *src);
1199 if (!isspace(*b)) break;
1204 // First digit is customized because we test for sign
1205 bool negative = false;
1206 /* static */ if (std::is_signed<Tgt>::value) {
1211 FOLLY_RANGE_CHECK_STRINGPIECE(*m == '+', "Invalid leading character in "
1212 "conversion to integral", *src);
1218 FOLLY_RANGE_CHECK_STRINGPIECE(m < past, "No digits found in input string",
1220 FOLLY_RANGE_CHECK_STRINGPIECE(isdigit(*m), "Non-digit character found", *src);
1221 m = detail::findFirstNonDigit<Tgt>(m + 1, past);
1224 /* static */ if (!std::is_signed<Tgt>::value) {
1225 result = detail::digits_to<typename std::make_unsigned<Tgt>::type>(b, m);
1227 auto t = detail::digits_to<typename std::make_unsigned<Tgt>::type>(b, m);
1230 FOLLY_RANGE_CHECK_STRINGPIECE(is_non_positive(result),
1231 "Negative overflow", *src);
1234 FOLLY_RANGE_CHECK_STRINGPIECE(is_non_negative(result), "Overflow", *src);
1237 src->advance(m - src->data());
1242 * StringPiece to bool, with progress information. Alters the
1243 * StringPiece parameter to munch the already-parsed characters.
1245 template <class Tgt>
1246 typename std::enable_if<
1247 std::is_same<typename std::remove_cv<Tgt>::type, bool>::value,
1249 to(StringPiece * src) {
1250 return detail::str_to_bool(src);
1256 * Enforce that the suffix following a number is made up only of whitespace.
1258 inline void enforceWhitespace(const char* b, const char* e) {
1259 for (; b != e; ++b) {
1260 FOLLY_RANGE_CHECK_BEGIN_END(isspace(*b),
1261 to<std::string>("Non-whitespace: ", *b),
1266 } // namespace detail
1269 * String or StringPiece to integrals. Accepts leading and trailing
1270 * whitespace, but no non-space trailing characters.
1272 template <class Tgt>
1273 typename std::enable_if<
1274 std::is_integral<Tgt>::value,
1276 to(StringPiece src) {
1277 Tgt result = to<Tgt>(&src);
1278 detail::enforceWhitespace(src.data(), src.data() + src.size());
1282 /*******************************************************************************
1283 * Conversions from string types to floating-point types.
1284 ******************************************************************************/
1287 * StringPiece to double, with progress information. Alters the
1288 * StringPiece parameter to munch the already-parsed characters.
1290 template <class Tgt>
1291 inline typename std::enable_if<
1292 std::is_floating_point<Tgt>::value,
1294 to(StringPiece *const src) {
1295 using namespace double_conversion;
1296 static StringToDoubleConverter
1297 conv(StringToDoubleConverter::ALLOW_TRAILING_JUNK
1298 | StringToDoubleConverter::ALLOW_LEADING_SPACES,
1300 // return this for junk input string
1301 std::numeric_limits<double>::quiet_NaN(),
1304 FOLLY_RANGE_CHECK_STRINGPIECE(!src->empty(),
1305 "No digits found in input string", *src);
1308 auto result = conv.StringToDouble(src->data(),
1309 static_cast<int>(src->size()),
1310 &length); // processed char count
1312 if (!std::isnan(result)) {
1313 src->advance(length);
1317 for (;; src->advance(1)) {
1319 throw std::range_error("Unable to convert an empty string"
1320 " to a floating point value.");
1322 if (!isspace(src->front())) {
1327 // Was that "inf[inity]"?
1328 if (src->size() >= 3 && toupper((*src)[0]) == 'I'
1329 && toupper((*src)[1]) == 'N' && toupper((*src)[2]) == 'F') {
1330 if (src->size() >= 8 &&
1331 toupper((*src)[3]) == 'I' &&
1332 toupper((*src)[4]) == 'N' &&
1333 toupper((*src)[5]) == 'I' &&
1334 toupper((*src)[6]) == 'T' &&
1335 toupper((*src)[7]) == 'Y') {
1340 return std::numeric_limits<Tgt>::infinity();
1343 // Was that "-inf[inity]"?
1344 if (src->size() >= 4 && toupper((*src)[0]) == '-'
1345 && toupper((*src)[1]) == 'I' && toupper((*src)[2]) == 'N'
1346 && toupper((*src)[3]) == 'F') {
1347 if (src->size() >= 9 &&
1348 toupper((*src)[4]) == 'I' &&
1349 toupper((*src)[5]) == 'N' &&
1350 toupper((*src)[6]) == 'I' &&
1351 toupper((*src)[7]) == 'T' &&
1352 toupper((*src)[8]) == 'Y') {
1357 return -std::numeric_limits<Tgt>::infinity();
1361 if (src->size() >= 3 && toupper((*src)[0]) == 'N'
1362 && toupper((*src)[1]) == 'A' && toupper((*src)[2]) == 'N') {
1364 return std::numeric_limits<Tgt>::quiet_NaN();
1368 if (src->size() >= 4 &&
1369 toupper((*src)[0]) == '-' &&
1370 toupper((*src)[1]) == 'N' &&
1371 toupper((*src)[2]) == 'A' &&
1372 toupper((*src)[3]) == 'N') {
1374 return -std::numeric_limits<Tgt>::quiet_NaN();
1378 throw std::range_error("Unable to convert \"" + src->toString()
1379 + "\" to a floating point value.");
1383 * Any string, const char*, or StringPiece to double.
1385 template <class Tgt>
1386 typename std::enable_if<
1387 std::is_floating_point<Tgt>::value,
1389 to(StringPiece src) {
1390 Tgt result = to<double>(&src);
1391 detail::enforceWhitespace(src.data(), src.data() + src.size());
1395 /*******************************************************************************
1396 * Integral to floating point and back
1397 ******************************************************************************/
1400 * Checked conversion from integral to flating point and back. The
1401 * result must be convertible back to the source type without loss of
1402 * precision. This seems Draconian but sometimes is what's needed, and
1403 * complements existing routines nicely. For various rounding
1404 * routines, see <math>.
1406 template <class Tgt, class Src>
1407 typename std::enable_if<
1408 (std::is_integral<Src>::value && std::is_floating_point<Tgt>::value)
1410 (std::is_floating_point<Src>::value && std::is_integral<Tgt>::value),
1412 to(const Src & value) {
1414 auto witness = static_cast<Src>(result);
1415 if (value != witness) {
1416 throw std::range_error(
1417 to<std::string>("to<>: loss of precision when converting ", value,
1418 #ifdef FOLLY_HAS_RTTI
1419 " to type ", typeid(Tgt).name()
1428 /*******************************************************************************
1429 * Enum to anything and back
1430 ******************************************************************************/
1432 template <class Tgt, class Src>
1433 typename std::enable_if<
1434 std::is_enum<Src>::value && !std::is_same<Src, Tgt>::value, Tgt>::type
1435 to(const Src & value) {
1436 return to<Tgt>(static_cast<typename std::underlying_type<Src>::type>(value));
1439 template <class Tgt, class Src>
1440 typename std::enable_if<
1441 std::is_enum<Tgt>::value && !std::is_same<Src, Tgt>::value, Tgt>::type
1442 to(const Src & value) {
1443 return static_cast<Tgt>(to<typename std::underlying_type<Tgt>::type>(value));
1446 } // namespace folly
1448 // FOLLY_CONV_INTERNAL is defined by Conv.cpp. Keep the FOLLY_RANGE_CHECK
1449 // macro for use in Conv.cpp, but #undefine it everywhere else we are included,
1450 // to avoid defining this global macro name in other files that include Conv.h.
1451 #ifndef FOLLY_CONV_INTERNAL
1452 #undef FOLLY_RANGE_CHECK
1453 #undef FOLLY_RANGE_CHECK_BEGIN_END
1454 #undef FOLLY_RANGE_CHECK_STRINGPIECE
1455 #undef FOLLY_RANGE_CHECK_STRINGIZE
1456 #undef FOLLY_RANGE_CHECK_STRINGIZE2
1459 #endif /* FOLLY_BASE_CONV_H_ */