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 if (LIKELY(v < 10)) return result;
234 if (LIKELY(v < 100)) return result + 1;
235 if (LIKELY(v < 1000)) return result + 2;
236 if (LIKELY(v < 10000)) return result + 3;
237 // Skip ahead by 4 orders of magnitude
244 * Copies the ASCII base 10 representation of v into buffer and
245 * returns the number of bytes written. Does NOT append a \0. Assumes
246 * the buffer points to digits10(v) bytes of valid memory. Note that
247 * uint64 needs at most 20 bytes, uint32_t needs at most 10 bytes,
248 * uint16_t needs at most 5 bytes, and so on. Measurements suggest
249 * that defining a separate overload for 32-bit integers is not
252 * This primitive is unsafe because it makes the size assumption and
253 * because it does not add a terminating \0.
256 inline uint32_t uint64ToBufferUnsafe(uint64_t v, char *const buffer) {
257 auto const result = digits10(v);
258 // WARNING: using size_t or pointer arithmetic for pos slows down
259 // the loop below 20x. This is because several 32-bit ops can be
260 // done in parallel, but only fewer 64-bit ones.
261 uint32_t pos = result - 1;
263 // Keep these together so a peephole optimization "sees" them and
264 // computes them in one shot.
265 auto const q = v / 10;
266 auto const r = static_cast<uint32_t>(v % 10);
267 buffer[pos--] = '0' + r;
270 // Last digit is trivial to handle
271 buffer[pos] = static_cast<uint32_t>(v) + '0';
276 * A single char gets appended.
279 void toAppend(char value, Tgt * result) {
284 constexpr typename std::enable_if<
285 std::is_same<T, char>::value,
287 estimateSpaceNeeded(T) {
292 * Ubiquitous helper template for writing string appenders
294 template <class T> struct IsSomeString {
295 enum { value = std::is_same<T, std::string>::value
296 || std::is_same<T, fbstring>::value };
300 * Everything implicitly convertible to const char* gets appended.
302 template <class Tgt, class Src>
303 typename std::enable_if<
304 std::is_convertible<Src, const char*>::value
305 && IsSomeString<Tgt>::value>::type
306 toAppend(Src value, Tgt * result) {
307 // Treat null pointers like an empty string, as in:
308 // operator<<(std::ostream&, const char*).
309 const char* c = value;
311 result->append(value);
316 typename std::enable_if<
317 std::is_convertible<Src, const char*>::value,
319 estimateSpaceNeeded(Src value) {
320 const char *c = value;
322 return folly::StringPiece(value).size();
328 typename std::enable_if<
329 (std::is_convertible<Src, folly::StringPiece>::value ||
330 IsSomeString<Src>::value) &&
331 !std::is_convertible<Src, const char*>::value,
333 estimateSpaceNeeded(Src value) {
334 return folly::StringPiece(value).size();
338 typename std::enable_if<
339 std::is_pointer<Src>::value &&
340 IsSomeString<std::remove_pointer<Src>>::value,
342 estimateSpaceNeeded(Src value) {
343 return value->size();
347 * Strings get appended, too.
349 template <class Tgt, class Src>
350 typename std::enable_if<
351 IsSomeString<Src>::value && IsSomeString<Tgt>::value>::type
352 toAppend(const Src& value, Tgt * result) {
353 result->append(value);
357 * and StringPiece objects too
360 typename std::enable_if<
361 IsSomeString<Tgt>::value>::type
362 toAppend(StringPiece value, Tgt * result) {
363 result->append(value.data(), value.size());
367 * There's no implicit conversion from fbstring to other string types,
368 * so make a specialization.
371 typename std::enable_if<
372 IsSomeString<Tgt>::value>::type
373 toAppend(const fbstring& value, Tgt * result) {
374 result->append(value.data(), value.size());
377 #if FOLLY_HAVE_INT128_T
379 * Special handling for 128 bit integers.
384 toAppend(__int128 value, Tgt * result) {
385 typedef unsigned __int128 Usrc;
386 char buffer[detail::digitsEnough<unsigned __int128>() + 1];
390 p = detail::unsafeTelescope128(buffer, sizeof(buffer), Usrc(-value));
393 p = detail::unsafeTelescope128(buffer, sizeof(buffer), value);
396 result->append(buffer + p, buffer + sizeof(buffer));
401 toAppend(unsigned __int128 value, Tgt * result) {
402 char buffer[detail::digitsEnough<unsigned __int128>()];
405 p = detail::unsafeTelescope128(buffer, sizeof(buffer), value);
407 result->append(buffer + p, buffer + sizeof(buffer));
411 constexpr typename std::enable_if<
412 std::is_same<T, __int128>::value,
414 estimateSpaceNeeded(T) {
415 return detail::digitsEnough<__int128>();
419 constexpr typename std::enable_if<
420 std::is_same<T, unsigned __int128>::value,
422 estimateSpaceNeeded(T) {
423 return detail::digitsEnough<unsigned __int128>();
429 * int32_t and int64_t to string (by appending) go through here. The
430 * result is APPENDED to a preexisting string passed as the second
431 * parameter. This should be efficient with fbstring because fbstring
432 * incurs no dynamic allocation below 23 bytes and no number has more
433 * than 22 bytes in its textual representation (20 for digits, one for
434 * sign, one for the terminating 0).
436 template <class Tgt, class Src>
437 typename std::enable_if<
438 std::is_integral<Src>::value && std::is_signed<Src>::value &&
439 IsSomeString<Tgt>::value && sizeof(Src) >= 4>::type
440 toAppend(Src value, Tgt * result) {
443 result->push_back('-');
444 result->append(buffer, uint64ToBufferUnsafe(-uint64_t(value), buffer));
446 result->append(buffer, uint64ToBufferUnsafe(value, buffer));
451 typename std::enable_if<
452 std::is_integral<Src>::value && std::is_signed<Src>::value
453 && sizeof(Src) >= 4 && sizeof(Src) < 16,
455 estimateSpaceNeeded(Src value) {
457 return 1 + digits10(static_cast<uint64_t>(-value));
460 return digits10(static_cast<uint64_t>(value));
464 * As above, but for uint32_t and uint64_t.
466 template <class Tgt, class Src>
467 typename std::enable_if<
468 std::is_integral<Src>::value && !std::is_signed<Src>::value
469 && IsSomeString<Tgt>::value && sizeof(Src) >= 4>::type
470 toAppend(Src value, Tgt * result) {
472 result->append(buffer, buffer + uint64ToBufferUnsafe(value, buffer));
476 typename std::enable_if<
477 std::is_integral<Src>::value && !std::is_signed<Src>::value
478 && sizeof(Src) >= 4 && sizeof(Src) < 16,
480 estimateSpaceNeeded(Src value) {
481 return digits10(value);
485 * All small signed and unsigned integers to string go through 32-bit
486 * types int32_t and uint32_t, respectively.
488 template <class Tgt, class Src>
489 typename std::enable_if<
490 std::is_integral<Src>::value
491 && IsSomeString<Tgt>::value && sizeof(Src) < 4>::type
492 toAppend(Src value, Tgt * result) {
494 std::conditional<std::is_signed<Src>::value, int64_t, uint64_t>::type
496 toAppend<Tgt>(static_cast<Intermediate>(value), result);
500 typename std::enable_if<
501 std::is_integral<Src>::value
503 && !std::is_same<Src, char>::value,
505 estimateSpaceNeeded(Src value) {
507 std::conditional<std::is_signed<Src>::value, int64_t, uint64_t>::type
509 return estimateSpaceNeeded(static_cast<Intermediate>(value));
512 #if defined(__clang__) || __GNUC_PREREQ(4, 7)
513 // std::underlying_type became available by gcc 4.7.0
516 * Enumerated values get appended as integers.
518 template <class Tgt, class Src>
519 typename std::enable_if<
520 std::is_enum<Src>::value && IsSomeString<Tgt>::value>::type
521 toAppend(Src value, Tgt * result) {
523 static_cast<typename std::underlying_type<Src>::type>(value), result);
527 typename std::enable_if<
528 std::is_enum<Src>::value, size_t>::type
529 estimateSpaceNeeded(Src value) {
530 return estimateSpaceNeeded(
531 static_cast<typename std::underlying_type<Src>::type>(value));
537 * Enumerated values get appended as integers.
539 template <class Tgt, class Src>
540 typename std::enable_if<
541 std::is_enum<Src>::value && IsSomeString<Tgt>::value>::type
542 toAppend(Src value, Tgt * result) {
543 /* static */ if (Src(-1) < 0) {
544 /* static */ if (sizeof(Src) <= sizeof(int)) {
545 toAppend(static_cast<int>(value), result);
547 toAppend(static_cast<long>(value), result);
550 /* static */ if (sizeof(Src) <= sizeof(int)) {
551 toAppend(static_cast<unsigned int>(value), result);
553 toAppend(static_cast<unsigned long>(value), result);
559 typename std::enable_if<
560 std::is_enum<Src>::value, size_t>::type
561 estimateSpaceNeeded(Src value) {
562 /* static */ if (Src(-1) < 0) {
563 /* static */ if (sizeof(Src) <= sizeof(int)) {
564 return estimateSpaceNeeded(static_cast<int>(value));
566 return estimateSpaceNeeded(static_cast<long>(value));
569 /* static */ if (sizeof(Src) <= sizeof(int)) {
570 return estimateSpaceNeeded(static_cast<unsigned int>(value));
572 return estimateSpaceNeeded(static_cast<unsigned long>(value));
577 #endif // gcc 4.7 onwards
579 /*******************************************************************************
580 * Conversions from floating-point types to string types.
581 ******************************************************************************/
584 constexpr int kConvMaxDecimalInShortestLow = -6;
585 constexpr int kConvMaxDecimalInShortestHigh = 21;
588 /** Wrapper around DoubleToStringConverter **/
589 template <class Tgt, class Src>
590 typename std::enable_if<
591 std::is_floating_point<Src>::value
592 && IsSomeString<Tgt>::value>::type
596 double_conversion::DoubleToStringConverter::DtoaMode mode,
597 unsigned int numDigits) {
598 using namespace double_conversion;
599 DoubleToStringConverter
600 conv(DoubleToStringConverter::NO_FLAGS,
601 "infinity", "NaN", 'E',
602 detail::kConvMaxDecimalInShortestLow,
603 detail::kConvMaxDecimalInShortestHigh,
604 6, // max leading padding zeros
605 1); // max trailing padding zeros
607 StringBuilder builder(buffer, sizeof(buffer));
609 case DoubleToStringConverter::SHORTEST:
610 conv.ToShortest(value, &builder);
612 case DoubleToStringConverter::FIXED:
613 conv.ToFixed(value, numDigits, &builder);
616 CHECK(mode == DoubleToStringConverter::PRECISION);
617 conv.ToPrecision(value, numDigits, &builder);
620 const size_t length = builder.position();
622 result->append(buffer, length);
626 * As above, but for floating point
628 template <class Tgt, class Src>
629 typename std::enable_if<
630 std::is_floating_point<Src>::value
631 && IsSomeString<Tgt>::value>::type
632 toAppend(Src value, Tgt * result) {
634 value, result, double_conversion::DoubleToStringConverter::SHORTEST, 0);
638 * Upper bound of the length of the output from
639 * DoubleToStringConverter::ToShortest(double, StringBuilder*),
640 * as used in toAppend(double, string*).
643 typename std::enable_if<
644 std::is_floating_point<Src>::value, size_t>::type
645 estimateSpaceNeeded(Src value) {
646 // kBase10MaximalLength is 17. We add 1 for decimal point,
647 // e.g. 10.0/9 is 17 digits and 18 characters, including the decimal point.
648 constexpr int kMaxMantissaSpace =
649 double_conversion::DoubleToStringConverter::kBase10MaximalLength + 1;
650 // strlen("E-") + digits10(numeric_limits<double>::max_exponent10)
651 constexpr int kMaxExponentSpace = 2 + 3;
652 static const int kMaxPositiveSpace = std::max({
653 // E.g. 1.1111111111111111E-100.
654 kMaxMantissaSpace + kMaxExponentSpace,
655 // E.g. 0.000001.1111111111111111, if kConvMaxDecimalInShortestLow is -6.
656 kMaxMantissaSpace - detail::kConvMaxDecimalInShortestLow,
657 // If kConvMaxDecimalInShortestHigh is 21, then 1e21 is the smallest
658 // number > 1 which ToShortest outputs in exponential notation,
659 // so 21 is the longest non-exponential number > 1.
660 detail::kConvMaxDecimalInShortestHigh
662 return kMaxPositiveSpace + (value < 0); // +1 for minus sign, if negative
666 * This can be specialized, together with adding specialization
667 * for estimateSpaceNeed for your type, so that we allocate
668 * as much as you need instead of the default
671 struct HasLengthEstimator : std::false_type {};
674 constexpr typename std::enable_if<
675 !std::is_fundamental<Src>::value
676 #ifdef FOLLY_HAVE_INT128_T
677 // On OSX 10.10, is_fundamental<__int128> is false :-O
678 && !std::is_same<__int128, Src>::value
679 && !std::is_same<unsigned __int128, Src>::value
681 && !IsSomeString<Src>::value
682 && !std::is_convertible<Src, const char*>::value
683 && !std::is_convertible<Src, StringPiece>::value
684 && !std::is_enum<Src>::value
685 && !HasLengthEstimator<Src>::value,
687 estimateSpaceNeeded(const Src&) {
688 return sizeof(Src) + 1; // dumbest best effort ever?
693 inline size_t estimateSpaceToReserve(size_t sofar) {
697 template <class T, class... Ts>
698 size_t estimateSpaceToReserve(size_t sofar, const T& v, const Ts&... vs) {
699 return estimateSpaceToReserve(sofar + estimateSpaceNeeded(v), vs...);
703 size_t estimateSpaceToReserve(size_t sofar, const T& v) {
704 return sofar + estimateSpaceNeeded(v);
708 void reserveInTarget(const Ts&...vs) {
709 getLastElement(vs...)->reserve(estimateSpaceToReserve(0, vs...));
712 template<class Delimiter, class...Ts>
713 void reserveInTargetDelim(const Delimiter& d, const Ts&...vs) {
714 static_assert(sizeof...(vs) >= 2, "Needs at least 2 args");
715 size_t fordelim = (sizeof...(vs) - 2) * estimateSpaceToReserve(0, d);
716 getLastElement(vs...)->reserve(estimateSpaceToReserve(fordelim, vs...));
720 * Variadic base case: append one element
722 template <class T, class Tgt>
723 typename std::enable_if<
724 IsSomeString<typename std::remove_pointer<Tgt>::type>
726 toAppendStrImpl(const T& v, Tgt result) {
730 template <class T, class... Ts>
731 typename std::enable_if<sizeof...(Ts) >= 2
733 typename std::remove_pointer<
734 typename detail::last_element<Ts...>::type
735 >::type>::value>::type
736 toAppendStrImpl(const T& v, const Ts&... vs) {
737 toAppend(v, getLastElement(vs...));
738 toAppendStrImpl(vs...);
741 template <class Delimiter, class T, class Tgt>
742 typename std::enable_if<
743 IsSomeString<typename std::remove_pointer<Tgt>::type>
745 toAppendDelimStrImpl(const Delimiter& delim, const T& v, Tgt result) {
749 template <class Delimiter, class T, class... Ts>
750 typename std::enable_if<sizeof...(Ts) >= 2
752 typename std::remove_pointer<
753 typename detail::last_element<Ts...>::type
754 >::type>::value>::type
755 toAppendDelimStrImpl(const Delimiter& delim, const T& v, const Ts&... vs) {
756 // we are really careful here, calling toAppend with just one element does
757 // not try to estimate space needed (as we already did that). If we call
758 // toAppend(v, delim, ....) we would do unnecesary size calculation
759 toAppend(v, detail::getLastElement(vs...));
760 toAppend(delim, detail::getLastElement(vs...));
761 toAppendDelimStrImpl(delim, vs...);
767 * Variadic conversion to string. Appends each element in turn.
768 * If we have two or more things to append, we it will not reserve
769 * the space for them and will depend on strings exponential growth.
770 * If you just append once consider using toAppendFit which reserves
771 * the space needed (but does not have exponential as a result).
773 template <class... Ts>
774 typename std::enable_if<sizeof...(Ts) >= 3
776 typename std::remove_pointer<
777 typename detail::last_element<Ts...>::type
778 >::type>::value>::type
779 toAppend(const Ts&... vs) {
780 detail::toAppendStrImpl(vs...);
784 * Special version of the call that preallocates exaclty as much memory
785 * as need for arguments to be stored in target. This means we are
786 * not doing exponential growth when we append. If you are using it
787 * in a loop you are aiming at your foot with a big perf-destroying
789 * On the other hand if you are appending to a string once, this
790 * will probably save a few calls to malloc.
792 template <class... Ts>
793 typename std::enable_if<
795 typename std::remove_pointer<
796 typename detail::last_element<Ts...>::type
797 >::type>::value>::type
798 toAppendFit(const Ts&... vs) {
799 detail::reserveInTarget(vs...);
804 void toAppendFit(const Ts&) {}
807 * Variadic base case: do nothing.
810 typename std::enable_if<IsSomeString<Tgt>::value>::type
811 toAppend(Tgt* result) {
815 * Variadic base case: do nothing.
817 template <class Delimiter, class Tgt>
818 typename std::enable_if<IsSomeString<Tgt>::value>::type
819 toAppendDelim(const Delimiter& delim, Tgt* result) {
823 * 1 element: same as toAppend.
825 template <class Delimiter, class T, class Tgt>
826 typename std::enable_if<IsSomeString<Tgt>::value>::type
827 toAppendDelim(const Delimiter& delim, const T& v, Tgt* tgt) {
832 * Append to string with a delimiter in between elements. Check out
833 * comments for toAppend for details about memory allocation.
835 template <class Delimiter, class... Ts>
836 typename std::enable_if<sizeof...(Ts) >= 3
838 typename std::remove_pointer<
839 typename detail::last_element<Ts...>::type
840 >::type>::value>::type
841 toAppendDelim(const Delimiter& delim, const Ts&... vs) {
842 detail::toAppendDelimStrImpl(delim, vs...);
846 * Detail in comment for toAppendFit
848 template <class Delimiter, class... Ts>
849 typename std::enable_if<
851 typename std::remove_pointer<
852 typename detail::last_element<Ts...>::type
853 >::type>::value>::type
854 toAppendDelimFit(const Delimiter& delim, const Ts&... vs) {
855 detail::reserveInTargetDelim(delim, vs...);
856 toAppendDelim(delim, vs...);
859 template <class De, class Ts>
860 void toAppendDelimFit(const De&, const Ts&) {}
863 * to<SomeString>(v1, v2, ...) uses toAppend() (see below) as back-end
866 template <class Tgt, class... Ts>
867 typename std::enable_if<
868 IsSomeString<Tgt>::value && (
869 sizeof...(Ts) != 1 ||
870 !std::is_same<Tgt, typename detail::last_element<Ts...>::type>::value),
872 to(const Ts&... vs) {
874 toAppendFit(vs..., &result);
879 * toDelim<SomeString>(SomeString str) returns itself.
881 template <class Tgt, class Delim, class Src>
882 typename std::enable_if<
883 IsSomeString<Tgt>::value && std::is_same<Tgt, Src>::value,
885 toDelim(const Delim& delim, const Src & value) {
890 * toDelim<SomeString>(delim, v1, v2, ...) uses toAppendDelim() as
891 * back-end for all types.
893 template <class Tgt, class Delim, class... Ts>
894 typename std::enable_if<
895 IsSomeString<Tgt>::value && (
896 sizeof...(Ts) != 1 ||
897 !std::is_same<Tgt, typename detail::last_element<Ts...>::type>::value),
899 toDelim(const Delim& delim, const Ts&... vs) {
901 toAppendDelimFit(delim, vs..., &result);
905 /*******************************************************************************
906 * Conversions from string types to integral types.
907 ******************************************************************************/
912 * Finds the first non-digit in a string. The number of digits
913 * searched depends on the precision of the Tgt integral. Assumes the
914 * string starts with NO whitespace and NO sign.
916 * The semantics of the routine is:
918 * if (b >= e || !isdigit(*b)) return b;
921 * Complete unrolling marks bottom-line (i.e. entire conversion)
922 * improvements of 20%.
925 const char* findFirstNonDigit(const char* b, const char* e) {
927 auto const c = static_cast<unsigned>(*b) - '0';
933 // Maximum value of number when represented as a string
934 template <class T> struct MaxString {
935 static const char*const value;
940 * Lookup tables that converts from a decimal character value to an integral
941 * binary value, shifted by a decimal "shift" multiplier.
942 * For all character values in the range '0'..'9', the table at those
943 * index locations returns the actual decimal value shifted by the multiplier.
944 * For all other values, the lookup table returns an invalid OOR value.
946 // Out-of-range flag value, larger than the largest value that can fit in
947 // four decimal bytes (9999), but four of these added up together should
948 // still not overflow uint16_t.
949 constexpr int32_t OOR = 10000;
951 __attribute__((__aligned__(16))) constexpr uint16_t shift1[] = {
952 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 0-9
953 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 10
954 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 20
955 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 30
956 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, 0, // 40
957 1, 2, 3, 4, 5, 6, 7, 8, 9, OOR, OOR,
958 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 60
959 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 70
960 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 80
961 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 90
962 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 100
963 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 110
964 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 120
965 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 130
966 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 140
967 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 150
968 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 160
969 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 170
970 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 180
971 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 190
972 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 200
973 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 210
974 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 220
975 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 230
976 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 240
977 OOR, OOR, OOR, OOR, OOR, OOR // 250
980 __attribute__((__aligned__(16))) constexpr uint16_t shift10[] = {
981 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 0-9
982 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 10
983 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 20
984 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 30
985 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, 0, // 40
986 10, 20, 30, 40, 50, 60, 70, 80, 90, OOR, OOR,
987 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 60
988 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 70
989 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 80
990 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 90
991 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 100
992 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 110
993 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 120
994 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 130
995 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 140
996 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 150
997 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 160
998 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 170
999 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 180
1000 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 190
1001 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 200
1002 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 210
1003 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 220
1004 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 230
1005 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 240
1006 OOR, OOR, OOR, OOR, OOR, OOR // 250
1009 __attribute__((__aligned__(16))) constexpr uint16_t shift100[] = {
1010 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 0-9
1011 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 10
1012 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 20
1013 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 30
1014 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, 0, // 40
1015 100, 200, 300, 400, 500, 600, 700, 800, 900, OOR, OOR,
1016 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 60
1017 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 70
1018 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 80
1019 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 90
1020 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 100
1021 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 110
1022 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 120
1023 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 130
1024 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 140
1025 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 150
1026 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 160
1027 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 170
1028 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 180
1029 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 190
1030 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 200
1031 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 210
1032 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 220
1033 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 230
1034 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 240
1035 OOR, OOR, OOR, OOR, OOR, OOR // 250
1038 __attribute__((__aligned__(16))) constexpr uint16_t shift1000[] = {
1039 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 0-9
1040 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 10
1041 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 20
1042 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 30
1043 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, 0, // 40
1044 1000, 2000, 3000, 4000, 5000, 6000, 7000, 8000, 9000, OOR, OOR,
1045 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 60
1046 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 70
1047 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 80
1048 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 90
1049 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 100
1050 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 110
1051 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 120
1052 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 130
1053 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 140
1054 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 150
1055 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 160
1056 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 170
1057 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 180
1058 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 190
1059 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 200
1060 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 210
1061 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 220
1062 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 230
1063 OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, // 240
1064 OOR, OOR, OOR, OOR, OOR, OOR // 250
1068 * String represented as a pair of pointers to char to unsigned
1069 * integrals. Assumes NO whitespace before or after, and also that the
1070 * string is composed entirely of digits. Tgt must be unsigned, and no
1071 * sign is allowed in the string (even it's '+'). String may be empty,
1072 * in which case digits_to throws.
1074 template <class Tgt>
1075 Tgt digits_to(const char * b, const char * e) {
1077 static_assert(!std::is_signed<Tgt>::value, "Unsigned type expected");
1080 const size_t size = e - b;
1082 /* Although the string is entirely made of digits, we still need to
1083 * check for overflow.
1085 if (size >= std::numeric_limits<Tgt>::digits10 + 1) {
1086 // Leading zeros? If so, recurse to keep things simple
1087 if (b < e && *b == '0') {
1089 if (b == e) return 0; // just zeros, e.g. "0000"
1090 if (*b != '0') return digits_to<Tgt>(b, e);
1093 FOLLY_RANGE_CHECK_BEGIN_END(
1094 size == std::numeric_limits<Tgt>::digits10 + 1 &&
1095 strncmp(b, detail::MaxString<Tgt>::value, size) <= 0,
1096 "Numeric overflow upon conversion", b, e);
1099 // Here we know that the number won't overflow when
1100 // converted. Proceed without checks.
1104 for (; e - b >= 4; b += 4) {
1106 const int32_t r0 = shift1000[static_cast<size_t>(b[0])];
1107 const int32_t r1 = shift100[static_cast<size_t>(b[1])];
1108 const int32_t r2 = shift10[static_cast<size_t>(b[2])];
1109 const int32_t r3 = shift1[static_cast<size_t>(b[3])];
1110 const auto sum = r0 + r1 + r2 + r3;
1111 assert(sum < OOR && "Assumption: string only has digits");
1117 const int32_t r0 = shift100[static_cast<size_t>(b[0])];
1118 const int32_t r1 = shift10[static_cast<size_t>(b[1])];
1119 const int32_t r2 = shift1[static_cast<size_t>(b[2])];
1120 const auto sum = r0 + r1 + r2;
1121 assert(sum < OOR && "Assumption: string only has digits");
1122 return result * 1000 + sum;
1125 const int32_t r0 = shift10[static_cast<size_t>(b[0])];
1126 const int32_t r1 = shift1[static_cast<size_t>(b[1])];
1127 const auto sum = r0 + r1;
1128 assert(sum < OOR && "Assumption: string only has digits");
1129 return result * 100 + sum;
1132 const int32_t sum = shift1[static_cast<size_t>(b[0])];
1133 assert(sum < OOR && "Assumption: string only has digits");
1134 return result * 10 + sum;
1139 FOLLY_RANGE_CHECK_BEGIN_END(size > 0,
1140 "Found no digits to convert in input", b, e);
1145 bool str_to_bool(StringPiece * src);
1147 } // namespace detail
1150 * String represented as a pair of pointers to char to unsigned
1151 * integrals. Assumes NO whitespace before or after.
1153 template <class Tgt>
1154 typename std::enable_if<
1155 std::is_integral<Tgt>::value && !std::is_signed<Tgt>::value
1156 && !std::is_same<typename std::remove_cv<Tgt>::type, bool>::value,
1158 to(const char * b, const char * e) {
1159 return detail::digits_to<Tgt>(b, e);
1163 * String represented as a pair of pointers to char to signed
1164 * integrals. Assumes NO whitespace before or after. Allows an
1165 * optional leading sign.
1167 template <class Tgt>
1168 typename std::enable_if<
1169 std::is_integral<Tgt>::value && std::is_signed<Tgt>::value,
1171 to(const char * b, const char * e) {
1172 FOLLY_RANGE_CHECK(b < e, "Empty input string in conversion to integral",
1173 to<std::string>("b: ", intptr_t(b), " e: ", intptr_t(e)));
1176 Tgt result = -to<typename std::make_unsigned<Tgt>::type>(b + 1, e);
1177 FOLLY_RANGE_CHECK_BEGIN_END(result <= 0, "Negative overflow.", b, e);
1180 FOLLY_RANGE_CHECK_BEGIN_END(*b == '+', "Invalid lead character", b, e);
1183 Tgt result = to<typename std::make_unsigned<Tgt>::type>(b, e);
1184 FOLLY_RANGE_CHECK_BEGIN_END(result >= 0, "Overflow", b, e);
1189 * Parsing strings to integrals. These routines differ from
1190 * to<integral>(string) in that they take a POINTER TO a StringPiece
1191 * and alter that StringPiece to reflect progress information.
1195 * StringPiece to integrals, with progress information. Alters the
1196 * StringPiece parameter to munch the already-parsed characters.
1198 template <class Tgt>
1199 typename std::enable_if<
1200 std::is_integral<Tgt>::value
1201 && !std::is_same<typename std::remove_cv<Tgt>::type, bool>::value,
1203 to(StringPiece * src) {
1205 auto b = src->data(), past = src->data() + src->size();
1207 FOLLY_RANGE_CHECK_STRINGPIECE(b < past,
1208 "No digits found in input string", *src);
1209 if (!isspace(*b)) break;
1214 // First digit is customized because we test for sign
1215 bool negative = false;
1216 /* static */ if (std::is_signed<Tgt>::value) {
1221 FOLLY_RANGE_CHECK_STRINGPIECE(*m == '+', "Invalid leading character in "
1222 "conversion to integral", *src);
1228 FOLLY_RANGE_CHECK_STRINGPIECE(m < past, "No digits found in input string",
1230 FOLLY_RANGE_CHECK_STRINGPIECE(isdigit(*m), "Non-digit character found", *src);
1231 m = detail::findFirstNonDigit<Tgt>(m + 1, past);
1234 /* static */ if (!std::is_signed<Tgt>::value) {
1235 result = detail::digits_to<typename std::make_unsigned<Tgt>::type>(b, m);
1237 auto t = detail::digits_to<typename std::make_unsigned<Tgt>::type>(b, m);
1240 FOLLY_RANGE_CHECK_STRINGPIECE(is_non_positive(result),
1241 "Negative overflow", *src);
1244 FOLLY_RANGE_CHECK_STRINGPIECE(is_non_negative(result), "Overflow", *src);
1247 src->advance(m - src->data());
1252 * StringPiece to bool, with progress information. Alters the
1253 * StringPiece parameter to munch the already-parsed characters.
1255 template <class Tgt>
1256 typename std::enable_if<
1257 std::is_same<typename std::remove_cv<Tgt>::type, bool>::value,
1259 to(StringPiece * src) {
1260 return detail::str_to_bool(src);
1266 * Enforce that the suffix following a number is made up only of whitespace.
1268 inline void enforceWhitespace(const char* b, const char* e) {
1269 for (; b != e; ++b) {
1270 FOLLY_RANGE_CHECK_BEGIN_END(isspace(*b),
1271 to<std::string>("Non-whitespace: ", *b),
1276 } // namespace detail
1279 * String or StringPiece to integrals. Accepts leading and trailing
1280 * whitespace, but no non-space trailing characters.
1282 template <class Tgt>
1283 typename std::enable_if<
1284 std::is_integral<Tgt>::value,
1286 to(StringPiece src) {
1287 Tgt result = to<Tgt>(&src);
1288 detail::enforceWhitespace(src.data(), src.data() + src.size());
1292 /*******************************************************************************
1293 * Conversions from string types to floating-point types.
1294 ******************************************************************************/
1297 * StringPiece to double, with progress information. Alters the
1298 * StringPiece parameter to munch the already-parsed characters.
1300 template <class Tgt>
1301 inline typename std::enable_if<
1302 std::is_floating_point<Tgt>::value,
1304 to(StringPiece *const src) {
1305 using namespace double_conversion;
1306 static StringToDoubleConverter
1307 conv(StringToDoubleConverter::ALLOW_TRAILING_JUNK
1308 | StringToDoubleConverter::ALLOW_LEADING_SPACES,
1310 // return this for junk input string
1311 std::numeric_limits<double>::quiet_NaN(),
1314 FOLLY_RANGE_CHECK_STRINGPIECE(!src->empty(),
1315 "No digits found in input string", *src);
1318 auto result = conv.StringToDouble(src->data(),
1319 static_cast<int>(src->size()),
1320 &length); // processed char count
1322 if (!std::isnan(result)) {
1323 src->advance(length);
1327 for (;; src->advance(1)) {
1329 throw std::range_error("Unable to convert an empty string"
1330 " to a floating point value.");
1332 if (!isspace(src->front())) {
1337 // Was that "inf[inity]"?
1338 if (src->size() >= 3 && toupper((*src)[0]) == 'I'
1339 && toupper((*src)[1]) == 'N' && toupper((*src)[2]) == 'F') {
1340 if (src->size() >= 8 &&
1341 toupper((*src)[3]) == 'I' &&
1342 toupper((*src)[4]) == 'N' &&
1343 toupper((*src)[5]) == 'I' &&
1344 toupper((*src)[6]) == 'T' &&
1345 toupper((*src)[7]) == 'Y') {
1350 return std::numeric_limits<Tgt>::infinity();
1353 // Was that "-inf[inity]"?
1354 if (src->size() >= 4 && toupper((*src)[0]) == '-'
1355 && toupper((*src)[1]) == 'I' && toupper((*src)[2]) == 'N'
1356 && toupper((*src)[3]) == 'F') {
1357 if (src->size() >= 9 &&
1358 toupper((*src)[4]) == 'I' &&
1359 toupper((*src)[5]) == 'N' &&
1360 toupper((*src)[6]) == 'I' &&
1361 toupper((*src)[7]) == 'T' &&
1362 toupper((*src)[8]) == 'Y') {
1367 return -std::numeric_limits<Tgt>::infinity();
1371 if (src->size() >= 3 && toupper((*src)[0]) == 'N'
1372 && toupper((*src)[1]) == 'A' && toupper((*src)[2]) == 'N') {
1374 return std::numeric_limits<Tgt>::quiet_NaN();
1378 if (src->size() >= 4 &&
1379 toupper((*src)[0]) == '-' &&
1380 toupper((*src)[1]) == 'N' &&
1381 toupper((*src)[2]) == 'A' &&
1382 toupper((*src)[3]) == 'N') {
1384 return -std::numeric_limits<Tgt>::quiet_NaN();
1388 throw std::range_error("Unable to convert \"" + src->toString()
1389 + "\" to a floating point value.");
1393 * Any string, const char*, or StringPiece to double.
1395 template <class Tgt>
1396 typename std::enable_if<
1397 std::is_floating_point<Tgt>::value,
1399 to(StringPiece src) {
1400 Tgt result = to<double>(&src);
1401 detail::enforceWhitespace(src.data(), src.data() + src.size());
1405 /*******************************************************************************
1406 * Integral to floating point and back
1407 ******************************************************************************/
1410 * Checked conversion from integral to flating point and back. The
1411 * result must be convertible back to the source type without loss of
1412 * precision. This seems Draconian but sometimes is what's needed, and
1413 * complements existing routines nicely. For various rounding
1414 * routines, see <math>.
1416 template <class Tgt, class Src>
1417 typename std::enable_if<
1418 (std::is_integral<Src>::value && std::is_floating_point<Tgt>::value)
1420 (std::is_floating_point<Src>::value && std::is_integral<Tgt>::value),
1422 to(const Src & value) {
1424 auto witness = static_cast<Src>(result);
1425 if (value != witness) {
1426 throw std::range_error(
1427 to<std::string>("to<>: loss of precision when converting ", value,
1428 " to type ", typeid(Tgt).name()).c_str());
1433 /*******************************************************************************
1434 * Enum to anything and back
1435 ******************************************************************************/
1437 #if defined(__clang__) || __GNUC_PREREQ(4, 7)
1438 // std::underlying_type became available by gcc 4.7.0
1440 template <class Tgt, class Src>
1441 typename std::enable_if<
1442 std::is_enum<Src>::value && !std::is_same<Src, Tgt>::value, Tgt>::type
1443 to(const Src & value) {
1444 return to<Tgt>(static_cast<typename std::underlying_type<Src>::type>(value));
1447 template <class Tgt, class Src>
1448 typename std::enable_if<
1449 std::is_enum<Tgt>::value && !std::is_same<Src, Tgt>::value, Tgt>::type
1450 to(const Src & value) {
1451 return static_cast<Tgt>(to<typename std::underlying_type<Tgt>::type>(value));
1456 template <class Tgt, class Src>
1457 typename std::enable_if<
1458 std::is_enum<Src>::value && !std::is_same<Src, Tgt>::value, Tgt>::type
1459 to(const Src & value) {
1460 /* static */ if (Src(-1) < 0) {
1461 /* static */ if (sizeof(Src) <= sizeof(int)) {
1462 return to<Tgt>(static_cast<int>(value));
1464 return to<Tgt>(static_cast<long>(value));
1467 /* static */ if (sizeof(Src) <= sizeof(int)) {
1468 return to<Tgt>(static_cast<unsigned int>(value));
1470 return to<Tgt>(static_cast<unsigned long>(value));
1475 template <class Tgt, class Src>
1476 typename std::enable_if<
1477 std::is_enum<Tgt>::value && !std::is_same<Src, Tgt>::value, Tgt>::type
1478 to(const Src & value) {
1479 /* static */ if (Tgt(-1) < 0) {
1480 /* static */ if (sizeof(Tgt) <= sizeof(int)) {
1481 return static_cast<Tgt>(to<int>(value));
1483 return static_cast<Tgt>(to<long>(value));
1486 /* static */ if (sizeof(Tgt) <= sizeof(int)) {
1487 return static_cast<Tgt>(to<unsigned int>(value));
1489 return static_cast<Tgt>(to<unsigned long>(value));
1494 #endif // gcc 4.7 onwards
1496 } // namespace folly
1498 // FOLLY_CONV_INTERNAL is defined by Conv.cpp. Keep the FOLLY_RANGE_CHECK
1499 // macro for use in Conv.cpp, but #undefine it everywhere else we are included,
1500 // to avoid defining this global macro name in other files that include Conv.h.
1501 #ifndef FOLLY_CONV_INTERNAL
1502 #undef FOLLY_RANGE_CHECK
1503 #undef FOLLY_RANGE_CHECK_BEGIN_END
1504 #undef FOLLY_RANGE_CHECK_STRINGPIECE
1505 #undef FOLLY_RANGE_CHECK_STRINGIZE
1506 #undef FOLLY_RANGE_CHECK_STRINGIZE2
1509 #endif /* FOLLY_BASE_CONV_H_ */