folly: to: make exceptions more informative
[folly.git] / folly / Conv.h
1 /*
2  * Copyright 2014 Facebook, Inc.
3  *
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
7  *
8  *   http://www.apache.org/licenses/LICENSE-2.0
9  *
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.
15  */
16
17 /**
18  * Converts anything to anything, with an emphasis on performance and
19  * safety.
20  *
21  * @author Andrei Alexandrescu (andrei.alexandrescu@fb.com)
22  */
23
24 #ifndef FOLLY_BASE_CONV_H_
25 #define FOLLY_BASE_CONV_H_
26
27 #include <folly/FBString.h>
28 #include <folly/Likely.h>
29 #include <folly/Preprocessor.h>
30 #include <folly/Range.h>
31
32 #include <boost/implicit_cast.hpp>
33 #include <algorithm>
34 #include <type_traits>
35 #include <limits>
36 #include <string>
37 #include <tuple>
38 #include <stdexcept>
39 #include <typeinfo>
40
41 #include <limits.h>
42
43 // V8 JavaScript implementation
44 #include <double-conversion/double-conversion.h>
45
46 #define FOLLY_RANGE_CHECK_STRINGIZE(x) #x
47 #define FOLLY_RANGE_CHECK_STRINGIZE2(x) FOLLY_RANGE_CHECK_STRINGIZE(x)
48
49 #define FOLLY_RANGE_CHECK(condition, message, src)                          \
50   ((condition) ? (void)0 : throw std::range_error(                          \
51     (std::string(__FILE__ "(" FOLLY_RANGE_CHECK_STRINGIZE2(__LINE__) "): ") \
52      + (message) + ": '" + (src) + "'").c_str()))
53
54 #define FOLLY_RANGE_CHECK_BEGIN_END(condition, message, b, e)    \
55   FOLLY_RANGE_CHECK(condition, message, std::string((b), (e) - (b)))
56
57 #define FOLLY_RANGE_CHECK_STRINGPIECE(condition, message, sp)    \
58   FOLLY_RANGE_CHECK(condition, message, std::string((sp).data(), (sp).size()))
59
60 namespace folly {
61
62 /**
63  * The identity conversion function.
64  * to<T>(T) returns itself for all types T.
65  */
66 template <class Tgt, class Src>
67 typename std::enable_if<std::is_same<Tgt, Src>::value, Tgt>::type
68 to(const Src & value) {
69   return value;
70 }
71
72 template <class Tgt, class Src>
73 typename std::enable_if<std::is_same<Tgt, Src>::value, Tgt>::type
74 to(Src && value) {
75   return std::move(value);
76 }
77
78 /*******************************************************************************
79  * Integral to integral
80  ******************************************************************************/
81
82 /**
83  * Checked conversion from integral to integral. The checks are only
84  * performed when meaningful, e.g. conversion from int to long goes
85  * unchecked.
86  */
87 template <class Tgt, class Src>
88 typename std::enable_if<
89   std::is_integral<Src>::value
90   && std::is_integral<Tgt>::value
91   && !std::is_same<Tgt, Src>::value,
92   Tgt>::type
93 to(const Src & value) {
94   /* static */ if (std::numeric_limits<Tgt>::max()
95                    < std::numeric_limits<Src>::max()) {
96     FOLLY_RANGE_CHECK(
97       (!greater_than<Tgt, std::numeric_limits<Tgt>::max()>(value)),
98       "Overflow", std::to_string(value)
99     );
100   }
101   /* static */ if (std::is_signed<Src>::value &&
102                    (!std::is_signed<Tgt>::value || sizeof(Src) > sizeof(Tgt))) {
103     FOLLY_RANGE_CHECK(
104       (!less_than<Tgt, std::numeric_limits<Tgt>::min()>(value)),
105       "Negative overflow", std::to_string(value)
106     );
107   }
108   return static_cast<Tgt>(value);
109 }
110
111 /*******************************************************************************
112  * Floating point to floating point
113  ******************************************************************************/
114
115 template <class Tgt, class Src>
116 typename std::enable_if<
117   std::is_floating_point<Tgt>::value
118   && std::is_floating_point<Src>::value
119   && !std::is_same<Tgt, Src>::value,
120   Tgt>::type
121 to(const Src & value) {
122   /* static */ if (std::numeric_limits<Tgt>::max() <
123                    std::numeric_limits<Src>::max()) {
124     FOLLY_RANGE_CHECK(value <= std::numeric_limits<Tgt>::max(),
125                       "Overflow", std::to_string(value));
126     FOLLY_RANGE_CHECK(value >= -std::numeric_limits<Tgt>::max(),
127                       "Negative overflow", std::to_string(value));
128   }
129   return boost::implicit_cast<Tgt>(value);
130 }
131
132 /*******************************************************************************
133  * Anything to string
134  ******************************************************************************/
135
136 namespace detail {
137
138 template <class T>
139 const T& getLastElement(const T & v) {
140   return v;
141 }
142
143 template <class T, class... Ts>
144 typename std::tuple_element<
145   sizeof...(Ts),
146   std::tuple<T, Ts...> >::type const&
147   getLastElement(const T& v, const Ts&... vs) {
148   return getLastElement(vs...);
149 }
150
151 // This class exists to specialize away std::tuple_element in the case where we
152 // have 0 template arguments. Without this, Clang/libc++ will blow a
153 // static_assert even if tuple_element is protected by an enable_if.
154 template <class... Ts>
155 struct last_element {
156   typedef typename std::enable_if<
157     sizeof...(Ts) >= 1,
158     typename std::tuple_element<
159       sizeof...(Ts) - 1, std::tuple<Ts...>
160     >::type>::type type;
161 };
162
163 template <>
164 struct last_element<> {
165   typedef void type;
166 };
167
168 } // namespace detail
169
170 /*******************************************************************************
171  * Conversions from integral types to string types.
172  ******************************************************************************/
173
174 #if FOLLY_HAVE_INT128_T
175 namespace detail {
176
177 template <typename IntegerType>
178 constexpr unsigned int
179 digitsEnough() {
180   return ceil((double(sizeof(IntegerType) * CHAR_BIT) * M_LN2) / M_LN10);
181 }
182
183 inline size_t
184 unsafeTelescope128(char * buffer, size_t room, unsigned __int128 x) {
185   typedef unsigned __int128 Usrc;
186   size_t p = room - 1;
187
188   while (x >= (Usrc(1) << 64)) { // Using 128-bit division while needed
189     const auto y = x / 10;
190     const auto digit = x % 10;
191
192     buffer[p--] = '0' + digit;
193     x = y;
194   }
195
196   uint64_t xx = x; // Moving to faster 64-bit division thereafter
197
198   while (xx >= 10) {
199     const auto y = xx / 10ULL;
200     const auto digit = xx % 10ULL;
201
202     buffer[p--] = '0' + digit;
203     xx = y;
204   }
205
206   buffer[p] = '0' + xx;
207
208   return p;
209 }
210
211 }
212 #endif
213
214 /**
215  * Returns the number of digits in the base 10 representation of an
216  * uint64_t. Useful for preallocating buffers and such. It's also used
217  * internally, see below. Measurements suggest that defining a
218  * separate overload for 32-bit integers is not worthwhile.
219  */
220
221 inline uint32_t digits10(uint64_t v) {
222   uint32_t result = 1;
223   for (;;) {
224     if (LIKELY(v < 10)) return result;
225     if (LIKELY(v < 100)) return result + 1;
226     if (LIKELY(v < 1000)) return result + 2;
227     if (LIKELY(v < 10000)) return result + 3;
228     // Skip ahead by 4 orders of magnitude
229     v /= 10000U;
230     result += 4;
231   }
232 }
233
234 /**
235  * Copies the ASCII base 10 representation of v into buffer and
236  * returns the number of bytes written. Does NOT append a \0. Assumes
237  * the buffer points to digits10(v) bytes of valid memory. Note that
238  * uint64 needs at most 20 bytes, uint32_t needs at most 10 bytes,
239  * uint16_t needs at most 5 bytes, and so on. Measurements suggest
240  * that defining a separate overload for 32-bit integers is not
241  * worthwhile.
242  *
243  * This primitive is unsafe because it makes the size assumption and
244  * because it does not add a terminating \0.
245  */
246
247 inline uint32_t uint64ToBufferUnsafe(uint64_t v, char *const buffer) {
248   auto const result = digits10(v);
249   // WARNING: using size_t or pointer arithmetic for pos slows down
250   // the loop below 20x. This is because several 32-bit ops can be
251   // done in parallel, but only fewer 64-bit ones.
252   uint32_t pos = result - 1;
253   while (v >= 10) {
254     // Keep these together so a peephole optimization "sees" them and
255     // computes them in one shot.
256     auto const q = v / 10;
257     auto const r = static_cast<uint32_t>(v % 10);
258     buffer[pos--] = '0' + r;
259     v = q;
260   }
261   // Last digit is trivial to handle
262   buffer[pos] = static_cast<uint32_t>(v) + '0';
263   return result;
264 }
265
266 /**
267  * A single char gets appended.
268  */
269 template <class Tgt>
270 void toAppend(char value, Tgt * result) {
271   *result += value;
272 }
273
274 template<class T>
275 constexpr typename std::enable_if<
276   std::is_same<T, char>::value,
277   size_t>::type
278 estimateSpaceNeeded(T) {
279   return 1;
280 }
281
282 /**
283  * Ubiquitous helper template for writing string appenders
284  */
285 template <class T> struct IsSomeString {
286   enum { value = std::is_same<T, std::string>::value
287          || std::is_same<T, fbstring>::value };
288 };
289
290 /**
291  * Everything implicitly convertible to const char* gets appended.
292  */
293 template <class Tgt, class Src>
294 typename std::enable_if<
295   std::is_convertible<Src, const char*>::value
296   && IsSomeString<Tgt>::value>::type
297 toAppend(Src value, Tgt * result) {
298   // Treat null pointers like an empty string, as in:
299   // operator<<(std::ostream&, const char*).
300   const char* c = value;
301   if (c) {
302     result->append(value);
303   }
304 }
305
306 template<class Src>
307 typename std::enable_if<
308   std::is_convertible<Src, const char*>::value,
309   size_t>::type
310 estimateSpaceNeeded(Src value) {
311   const char *c = value;
312   if (c) {
313     return folly::StringPiece(value).size();
314   };
315   return 0;
316 }
317
318 template<class Src>
319 typename std::enable_if<
320   (std::is_convertible<Src, folly::StringPiece>::value ||
321   IsSomeString<Src>::value) &&
322   !std::is_convertible<Src, const char*>::value,
323   size_t>::type
324 estimateSpaceNeeded(Src value) {
325   return folly::StringPiece(value).size();
326 }
327
328 template<class Src>
329 typename std::enable_if<
330   std::is_pointer<Src>::value &&
331   IsSomeString<std::remove_pointer<Src>>::value,
332   size_t>::type
333 estimateSpaceNeeded(Src value) {
334   return value->size();
335 }
336
337 /**
338  * Strings get appended, too.
339  */
340 template <class Tgt, class Src>
341 typename std::enable_if<
342   IsSomeString<Src>::value && IsSomeString<Tgt>::value>::type
343 toAppend(const Src& value, Tgt * result) {
344   result->append(value);
345 }
346
347 /**
348  * and StringPiece objects too
349  */
350 template <class Tgt>
351 typename std::enable_if<
352    IsSomeString<Tgt>::value>::type
353 toAppend(StringPiece value, Tgt * result) {
354   result->append(value.data(), value.size());
355 }
356
357 /**
358  * There's no implicit conversion from fbstring to other string types,
359  * so make a specialization.
360  */
361 template <class Tgt>
362 typename std::enable_if<
363    IsSomeString<Tgt>::value>::type
364 toAppend(const fbstring& value, Tgt * result) {
365   result->append(value.data(), value.size());
366 }
367
368 #if FOLLY_HAVE_INT128_T
369 /**
370  * Special handling for 128 bit integers.
371  */
372
373 template <class Tgt>
374 void
375 toAppend(__int128 value, Tgt * result) {
376   typedef unsigned __int128 Usrc;
377   char buffer[detail::digitsEnough<unsigned __int128>() + 1];
378   size_t p;
379
380   if (value < 0) {
381     p = detail::unsafeTelescope128(buffer, sizeof(buffer), Usrc(-value));
382     buffer[--p] = '-';
383   } else {
384     p = detail::unsafeTelescope128(buffer, sizeof(buffer), value);
385   }
386
387   result->append(buffer + p, buffer + sizeof(buffer));
388 }
389
390 template <class Tgt>
391 void
392 toAppend(unsigned __int128 value, Tgt * result) {
393   char buffer[detail::digitsEnough<unsigned __int128>()];
394   size_t p;
395
396   p = detail::unsafeTelescope128(buffer, sizeof(buffer), value);
397
398   result->append(buffer + p, buffer + sizeof(buffer));
399 }
400
401 template<class T>
402 constexpr typename std::enable_if<
403   std::is_same<T, __int128>::value,
404   size_t>::type
405 estimateSpaceNeeded(T) {
406   return detail::digitsEnough<__int128>();
407 }
408
409 template<class T>
410 constexpr typename std::enable_if<
411   std::is_same<T, unsigned __int128>::value,
412   size_t>::type
413 estimateSpaceNeeded(T) {
414   return detail::digitsEnough<unsigned __int128>();
415 }
416
417 #endif
418
419 /**
420  * int32_t and int64_t to string (by appending) go through here. The
421  * result is APPENDED to a preexisting string passed as the second
422  * parameter. This should be efficient with fbstring because fbstring
423  * incurs no dynamic allocation below 23 bytes and no number has more
424  * than 22 bytes in its textual representation (20 for digits, one for
425  * sign, one for the terminating 0).
426  */
427 template <class Tgt, class Src>
428 typename std::enable_if<
429   std::is_integral<Src>::value && std::is_signed<Src>::value &&
430   IsSomeString<Tgt>::value && sizeof(Src) >= 4>::type
431 toAppend(Src value, Tgt * result) {
432   char buffer[20];
433   if (value < 0) {
434     result->push_back('-');
435     result->append(buffer, uint64ToBufferUnsafe(-uint64_t(value), buffer));
436   } else {
437     result->append(buffer, uint64ToBufferUnsafe(value, buffer));
438   }
439 }
440
441 template <class Src>
442 typename std::enable_if<
443   std::is_integral<Src>::value && std::is_signed<Src>::value
444   && sizeof(Src) >= 4 && sizeof(Src) < 16,
445   size_t>::type
446 estimateSpaceNeeded(Src value) {
447   if (value < 0) {
448     return 1 + digits10(static_cast<uint64_t>(-value));
449   }
450
451   return digits10(static_cast<uint64_t>(value));
452 }
453
454 /**
455  * As above, but for uint32_t and uint64_t.
456  */
457 template <class Tgt, class Src>
458 typename std::enable_if<
459   std::is_integral<Src>::value && !std::is_signed<Src>::value
460   && IsSomeString<Tgt>::value && sizeof(Src) >= 4>::type
461 toAppend(Src value, Tgt * result) {
462   char buffer[20];
463   result->append(buffer, buffer + uint64ToBufferUnsafe(value, buffer));
464 }
465
466 template <class Src>
467 typename std::enable_if<
468   std::is_integral<Src>::value && !std::is_signed<Src>::value
469   && sizeof(Src) >= 4 && sizeof(Src) < 16,
470   size_t>::type
471 estimateSpaceNeeded(Src value) {
472   return digits10(value);
473 }
474
475 /**
476  * All small signed and unsigned integers to string go through 32-bit
477  * types int32_t and uint32_t, respectively.
478  */
479 template <class Tgt, class Src>
480 typename std::enable_if<
481   std::is_integral<Src>::value
482   && IsSomeString<Tgt>::value && sizeof(Src) < 4>::type
483 toAppend(Src value, Tgt * result) {
484   typedef typename
485     std::conditional<std::is_signed<Src>::value, int64_t, uint64_t>::type
486     Intermediate;
487   toAppend<Tgt>(static_cast<Intermediate>(value), result);
488 }
489
490 template <class Src>
491 typename std::enable_if<
492   std::is_integral<Src>::value
493   && sizeof(Src) < 4
494   && !std::is_same<Src, char>::value,
495   size_t>::type
496 estimateSpaceNeeded(Src value) {
497   typedef typename
498     std::conditional<std::is_signed<Src>::value, int64_t, uint64_t>::type
499     Intermediate;
500   return estimateSpaceNeeded(static_cast<Intermediate>(value));
501 }
502
503 #if defined(__clang__) || __GNUC_PREREQ(4, 7)
504 // std::underlying_type became available by gcc 4.7.0
505
506 /**
507  * Enumerated values get appended as integers.
508  */
509 template <class Tgt, class Src>
510 typename std::enable_if<
511   std::is_enum<Src>::value && IsSomeString<Tgt>::value>::type
512 toAppend(Src value, Tgt * result) {
513   toAppend(
514       static_cast<typename std::underlying_type<Src>::type>(value), result);
515 }
516
517 template <class Src>
518 typename std::enable_if<
519   std::is_enum<Src>::value, size_t>::type
520 estimateSpaceNeeded(Src value) {
521   return estimateSpaceNeeded(
522       static_cast<typename std::underlying_type<Src>::type>(value));
523 }
524
525 #else
526
527 /**
528  * Enumerated values get appended as integers.
529  */
530 template <class Tgt, class Src>
531 typename std::enable_if<
532   std::is_enum<Src>::value && IsSomeString<Tgt>::value>::type
533 toAppend(Src value, Tgt * result) {
534   /* static */ if (Src(-1) < 0) {
535     /* static */ if (sizeof(Src) <= sizeof(int)) {
536       toAppend(static_cast<int>(value), result);
537     } else {
538       toAppend(static_cast<long>(value), result);
539     }
540   } else {
541     /* static */ if (sizeof(Src) <= sizeof(int)) {
542       toAppend(static_cast<unsigned int>(value), result);
543     } else {
544       toAppend(static_cast<unsigned long>(value), result);
545     }
546   }
547 }
548
549 template <class Src>
550 typename std::enable_if<
551   std::is_enum<Src>::value, size_t>::type
552 estimateSpaceNeeded(Src value) {
553   /* static */ if (Src(-1) < 0) {
554     /* static */ if (sizeof(Src) <= sizeof(int)) {
555       return estimateSpaceNeeded(static_cast<int>(value));
556     } else {
557       return estimateSpaceNeeded(static_cast<long>(value));
558     }
559   } else {
560     /* static */ if (sizeof(Src) <= sizeof(int)) {
561       return estimateSpaceNeeded(static_cast<unsigned int>(value));
562     } else {
563       return estimateSpaceNeeded(static_cast<unsigned long>(value));
564     }
565   }
566 }
567
568 #endif // gcc 4.7 onwards
569
570 /*******************************************************************************
571  * Conversions from floating-point types to string types.
572  ******************************************************************************/
573
574 namespace detail {
575 constexpr int kConvMaxDecimalInShortestLow = -6;
576 constexpr int kConvMaxDecimalInShortestHigh = 21;
577 } // folly::detail
578
579 /** Wrapper around DoubleToStringConverter **/
580 template <class Tgt, class Src>
581 typename std::enable_if<
582   std::is_floating_point<Src>::value
583   && IsSomeString<Tgt>::value>::type
584 toAppend(
585   Src value,
586   Tgt * result,
587   double_conversion::DoubleToStringConverter::DtoaMode mode,
588   unsigned int numDigits) {
589   using namespace double_conversion;
590   DoubleToStringConverter
591     conv(DoubleToStringConverter::NO_FLAGS,
592          "infinity", "NaN", 'E',
593          detail::kConvMaxDecimalInShortestLow,
594          detail::kConvMaxDecimalInShortestHigh,
595          6,   // max leading padding zeros
596          1);  // max trailing padding zeros
597   char buffer[256];
598   StringBuilder builder(buffer, sizeof(buffer));
599   switch (mode) {
600     case DoubleToStringConverter::SHORTEST:
601       conv.ToShortest(value, &builder);
602       break;
603     case DoubleToStringConverter::FIXED:
604       conv.ToFixed(value, numDigits, &builder);
605       break;
606     default:
607       CHECK(mode == DoubleToStringConverter::PRECISION);
608       conv.ToPrecision(value, numDigits, &builder);
609       break;
610   }
611   const size_t length = builder.position();
612   builder.Finalize();
613   result->append(buffer, length);
614 }
615
616 /**
617  * As above, but for floating point
618  */
619 template <class Tgt, class Src>
620 typename std::enable_if<
621   std::is_floating_point<Src>::value
622   && IsSomeString<Tgt>::value>::type
623 toAppend(Src value, Tgt * result) {
624   toAppend(
625     value, result, double_conversion::DoubleToStringConverter::SHORTEST, 0);
626 }
627
628 /**
629  * Upper bound of the length of the output from
630  * DoubleToStringConverter::ToShortest(double, StringBuilder*),
631  * as used in toAppend(double, string*).
632  */
633 template <class Src>
634 typename std::enable_if<
635   std::is_floating_point<Src>::value, size_t>::type
636 estimateSpaceNeeded(Src value) {
637   // kBase10MaximalLength is 17. We add 1 for decimal point,
638   // e.g. 10.0/9 is 17 digits and 18 characters, including the decimal point.
639   constexpr int kMaxMantissaSpace =
640     double_conversion::DoubleToStringConverter::kBase10MaximalLength + 1;
641   // strlen("E-") + digits10(numeric_limits<double>::max_exponent10)
642   constexpr int kMaxExponentSpace = 2 + 3;
643   static const int kMaxPositiveSpace = std::max({
644       // E.g. 1.1111111111111111E-100.
645       kMaxMantissaSpace + kMaxExponentSpace,
646       // E.g. 0.000001.1111111111111111, if kConvMaxDecimalInShortestLow is -6.
647       kMaxMantissaSpace - detail::kConvMaxDecimalInShortestLow,
648       // If kConvMaxDecimalInShortestHigh is 21, then 1e21 is the smallest
649       // number > 1 which ToShortest outputs in exponential notation,
650       // so 21 is the longest non-exponential number > 1.
651       detail::kConvMaxDecimalInShortestHigh
652     });
653   return kMaxPositiveSpace + (value < 0);  // +1 for minus sign, if negative
654 }
655
656 /**
657  * This can be specialized, together with adding specialization
658  * for estimateSpaceNeed for your type, so that we allocate
659  * as much as you need instead of the default
660  */
661 template<class Src>
662 struct HasLengthEstimator : std::false_type {};
663
664 template <class Src>
665 constexpr typename std::enable_if<
666   !std::is_fundamental<Src>::value
667 #ifdef FOLLY_HAVE_INT128_T
668   // On OSX 10.10, is_fundamental<__int128> is false :-O
669   && !std::is_same<__int128, Src>::value
670   && !std::is_same<unsigned __int128, Src>::value
671 #endif
672   && !IsSomeString<Src>::value
673   && !std::is_convertible<Src, const char*>::value
674   && !std::is_convertible<Src, StringPiece>::value
675   && !std::is_enum<Src>::value
676   && !HasLengthEstimator<Src>::value,
677   size_t>::type
678 estimateSpaceNeeded(const Src&) {
679   return sizeof(Src) + 1; // dumbest best effort ever?
680 }
681
682 namespace detail {
683
684 inline size_t estimateSpaceToReserve(size_t sofar) {
685   return sofar;
686 }
687
688 template <class T, class... Ts>
689 size_t estimateSpaceToReserve(size_t sofar, const T& v, const Ts&... vs) {
690   return estimateSpaceToReserve(sofar + estimateSpaceNeeded(v), vs...);
691 }
692
693 template<class T>
694 size_t estimateSpaceToReserve(size_t sofar, const T& v) {
695   return sofar + estimateSpaceNeeded(v);
696 }
697
698 template<class...Ts>
699 void reserveInTarget(const Ts&...vs) {
700   getLastElement(vs...)->reserve(estimateSpaceToReserve(0, vs...));
701 }
702
703 template<class Delimiter, class...Ts>
704 void reserveInTargetDelim(const Delimiter& d, const Ts&...vs) {
705   static_assert(sizeof...(vs) >= 2, "Needs at least 2 args");
706   size_t fordelim = (sizeof...(vs) - 2) * estimateSpaceToReserve(0, d);
707   getLastElement(vs...)->reserve(estimateSpaceToReserve(fordelim, vs...));
708 }
709
710 /**
711  * Variadic base case: append one element
712  */
713 template <class T, class Tgt>
714 typename std::enable_if<
715   IsSomeString<typename std::remove_pointer<Tgt>::type>
716   ::value>::type
717 toAppendStrImpl(const T& v, Tgt result) {
718   toAppend(v, result);
719 }
720
721 template <class T, class... Ts>
722 typename std::enable_if<sizeof...(Ts) >= 2
723   && IsSomeString<
724   typename std::remove_pointer<
725     typename detail::last_element<Ts...>::type
726   >::type>::value>::type
727 toAppendStrImpl(const T& v, const Ts&... vs) {
728   toAppend(v, getLastElement(vs...));
729   toAppendStrImpl(vs...);
730 }
731
732 template <class Delimiter, class T, class Tgt>
733 typename std::enable_if<
734   IsSomeString<typename std::remove_pointer<Tgt>::type>
735   ::value>::type
736 toAppendDelimStrImpl(const Delimiter& delim, const T& v, Tgt result) {
737   toAppend(v, result);
738 }
739
740 template <class Delimiter, class T, class... Ts>
741 typename std::enable_if<sizeof...(Ts) >= 2
742   && IsSomeString<
743   typename std::remove_pointer<
744     typename detail::last_element<Ts...>::type
745   >::type>::value>::type
746 toAppendDelimStrImpl(const Delimiter& delim, const T& v, const Ts&... vs) {
747   // we are really careful here, calling toAppend with just one element does
748   // not try to estimate space needed (as we already did that). If we call
749   // toAppend(v, delim, ....) we would do unnecesary size calculation
750   toAppend(v, detail::getLastElement(vs...));
751   toAppend(delim, detail::getLastElement(vs...));
752   toAppendDelimStrImpl(delim, vs...);
753 }
754 } // folly::detail
755
756
757 /**
758  * Variadic conversion to string. Appends each element in turn.
759  * If we have two or more things to append, we it will not reserve
760  * the space for them and will depend on strings exponential growth.
761  * If you just append once consider using toAppendFit which reserves
762  * the space needed (but does not have exponential as a result).
763  */
764 template <class... Ts>
765 typename std::enable_if<sizeof...(Ts) >= 3
766   && IsSomeString<
767   typename std::remove_pointer<
768     typename detail::last_element<Ts...>::type
769   >::type>::value>::type
770 toAppend(const Ts&... vs) {
771   detail::toAppendStrImpl(vs...);
772 }
773
774 /**
775  * Special version of the call that preallocates exaclty as much memory
776  * as need for arguments to be stored in target. This means we are
777  * not doing exponential growth when we append. If you are using it
778  * in a loop you are aiming at your foot with a big perf-destroying
779  * bazooka.
780  * On the other hand if you are appending to a string once, this
781  * will probably save a few calls to malloc.
782  */
783 template <class... Ts>
784 typename std::enable_if<
785   IsSomeString<
786   typename std::remove_pointer<
787     typename detail::last_element<Ts...>::type
788   >::type>::value>::type
789 toAppendFit(const Ts&... vs) {
790   detail::reserveInTarget(vs...);
791   toAppend(vs...);
792 }
793
794 template <class Ts>
795 void toAppendFit(const Ts&) {}
796
797 /**
798  * Variadic base case: do nothing.
799  */
800 template <class Tgt>
801 typename std::enable_if<IsSomeString<Tgt>::value>::type
802 toAppend(Tgt* result) {
803 }
804
805 /**
806  * Variadic base case: do nothing.
807  */
808 template <class Delimiter, class Tgt>
809 typename std::enable_if<IsSomeString<Tgt>::value>::type
810 toAppendDelim(const Delimiter& delim, Tgt* result) {
811 }
812
813 /**
814  * 1 element: same as toAppend.
815  */
816 template <class Delimiter, class T, class Tgt>
817 typename std::enable_if<IsSomeString<Tgt>::value>::type
818 toAppendDelim(const Delimiter& delim, const T& v, Tgt* tgt) {
819   toAppend(v, tgt);
820 }
821
822 /**
823  * Append to string with a delimiter in between elements. Check out
824  * comments for toAppend for details about memory allocation.
825  */
826 template <class Delimiter, class... Ts>
827 typename std::enable_if<sizeof...(Ts) >= 3
828   && IsSomeString<
829   typename std::remove_pointer<
830     typename detail::last_element<Ts...>::type
831   >::type>::value>::type
832 toAppendDelim(const Delimiter& delim, const Ts&... vs) {
833   detail::toAppendDelimStrImpl(delim, vs...);
834 }
835
836 /**
837  * Detail in comment for toAppendFit
838  */
839 template <class Delimiter, class... Ts>
840 typename std::enable_if<
841   IsSomeString<
842   typename std::remove_pointer<
843     typename detail::last_element<Ts...>::type
844   >::type>::value>::type
845 toAppendDelimFit(const Delimiter& delim, const Ts&... vs) {
846   detail::reserveInTargetDelim(delim, vs...);
847   toAppendDelim(delim, vs...);
848 }
849
850 template <class De, class Ts>
851 void toAppendDelimFit(const De&, const Ts&) {}
852
853 /**
854  * to<SomeString>(v1, v2, ...) uses toAppend() (see below) as back-end
855  * for all types.
856  */
857 template <class Tgt, class... Ts>
858 typename std::enable_if<
859   IsSomeString<Tgt>::value && (
860     sizeof...(Ts) != 1 ||
861     !std::is_same<Tgt, typename detail::last_element<Ts...>::type>::value),
862   Tgt>::type
863 to(const Ts&... vs) {
864   Tgt result;
865   toAppendFit(vs..., &result);
866   return result;
867 }
868
869 /**
870  * toDelim<SomeString>(SomeString str) returns itself.
871  */
872 template <class Tgt, class Delim, class Src>
873 typename std::enable_if<
874   IsSomeString<Tgt>::value && std::is_same<Tgt, Src>::value,
875   Tgt>::type
876 toDelim(const Delim& delim, const Src & value) {
877   return value;
878 }
879
880 /**
881  * toDelim<SomeString>(delim, v1, v2, ...) uses toAppendDelim() as
882  * back-end for all types.
883  */
884 template <class Tgt, class Delim, class... Ts>
885 typename std::enable_if<
886   IsSomeString<Tgt>::value && (
887     sizeof...(Ts) != 1 ||
888     !std::is_same<Tgt, typename detail::last_element<Ts...>::type>::value),
889   Tgt>::type
890 toDelim(const Delim& delim, const Ts&... vs) {
891   Tgt result;
892   toAppendDelimFit(delim, vs..., &result);
893   return result;
894 }
895
896 /*******************************************************************************
897  * Conversions from string types to integral types.
898  ******************************************************************************/
899
900 namespace detail {
901
902 /**
903  * Finds the first non-digit in a string. The number of digits
904  * searched depends on the precision of the Tgt integral. Assumes the
905  * string starts with NO whitespace and NO sign.
906  *
907  * The semantics of the routine is:
908  *   for (;; ++b) {
909  *     if (b >= e || !isdigit(*b)) return b;
910  *   }
911  *
912  *  Complete unrolling marks bottom-line (i.e. entire conversion)
913  *  improvements of 20%.
914  */
915   template <class Tgt>
916   const char* findFirstNonDigit(const char* b, const char* e) {
917     for (; b < e; ++b) {
918       auto const c = static_cast<unsigned>(*b) - '0';
919       if (c >= 10) break;
920     }
921     return b;
922   }
923
924   // Maximum value of number when represented as a string
925   template <class T> struct MaxString {
926     static const char*const value;
927   };
928
929
930 /*
931  * Lookup tables that converts from a decimal character value to an integral
932  * binary value, shifted by a decimal "shift" multiplier.
933  * For all character values in the range '0'..'9', the table at those
934  * index locations returns the actual decimal value shifted by the multiplier.
935  * For all other values, the lookup table returns an invalid OOR value.
936  */
937 // Out-of-range flag value, larger than the largest value that can fit in
938 // four decimal bytes (9999), but four of these added up together should
939 // still not overflow uint16_t.
940 constexpr int32_t OOR = 10000;
941
942 __attribute__((__aligned__(16))) constexpr uint16_t shift1[] = {
943   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 0-9
944   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  //  10
945   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  //  20
946   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  //  30
947   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, 0,         //  40
948   1, 2, 3, 4, 5, 6, 7, 8, 9, OOR, OOR,
949   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  //  60
950   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  //  70
951   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  //  80
952   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  //  90
953   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 100
954   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 110
955   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 120
956   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 130
957   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 140
958   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 150
959   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 160
960   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 170
961   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 180
962   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 190
963   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 200
964   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 210
965   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 220
966   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 230
967   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 240
968   OOR, OOR, OOR, OOR, OOR, OOR                       // 250
969 };
970
971 __attribute__((__aligned__(16))) constexpr uint16_t shift10[] = {
972   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 0-9
973   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  //  10
974   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  //  20
975   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  //  30
976   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, 0,         //  40
977   10, 20, 30, 40, 50, 60, 70, 80, 90, OOR, OOR,
978   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  //  60
979   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  //  70
980   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  //  80
981   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  //  90
982   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 100
983   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 110
984   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 120
985   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 130
986   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 140
987   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 150
988   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 160
989   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 170
990   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 180
991   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 190
992   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 200
993   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 210
994   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 220
995   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 230
996   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 240
997   OOR, OOR, OOR, OOR, OOR, OOR                       // 250
998 };
999
1000 __attribute__((__aligned__(16))) constexpr uint16_t shift100[] = {
1001   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 0-9
1002   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  //  10
1003   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  //  20
1004   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  //  30
1005   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, 0,         //  40
1006   100, 200, 300, 400, 500, 600, 700, 800, 900, OOR, OOR,
1007   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  //  60
1008   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  //  70
1009   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  //  80
1010   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  //  90
1011   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 100
1012   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 110
1013   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 120
1014   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 130
1015   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 140
1016   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 150
1017   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 160
1018   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 170
1019   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 180
1020   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 190
1021   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 200
1022   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 210
1023   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 220
1024   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 230
1025   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 240
1026   OOR, OOR, OOR, OOR, OOR, OOR                       // 250
1027 };
1028
1029 __attribute__((__aligned__(16))) constexpr uint16_t shift1000[] = {
1030   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 0-9
1031   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  //  10
1032   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  //  20
1033   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  //  30
1034   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, 0,         //  40
1035   1000, 2000, 3000, 4000, 5000, 6000, 7000, 8000, 9000, OOR, OOR,
1036   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  //  60
1037   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  //  70
1038   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  //  80
1039   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  //  90
1040   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 100
1041   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 110
1042   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 120
1043   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 130
1044   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 140
1045   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 150
1046   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 160
1047   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 170
1048   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 180
1049   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 190
1050   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 200
1051   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 210
1052   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 220
1053   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 230
1054   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 240
1055   OOR, OOR, OOR, OOR, OOR, OOR                       // 250
1056 };
1057
1058 /**
1059  * String represented as a pair of pointers to char to unsigned
1060  * integrals. Assumes NO whitespace before or after, and also that the
1061  * string is composed entirely of digits. Tgt must be unsigned, and no
1062  * sign is allowed in the string (even it's '+'). String may be empty,
1063  * in which case digits_to throws.
1064  */
1065   template <class Tgt>
1066   Tgt digits_to(const char * b, const char * e) {
1067
1068     static_assert(!std::is_signed<Tgt>::value, "Unsigned type expected");
1069     assert(b <= e);
1070
1071     const size_t size = e - b;
1072
1073     /* Although the string is entirely made of digits, we still need to
1074      * check for overflow.
1075      */
1076     if (size >= std::numeric_limits<Tgt>::digits10 + 1) {
1077       // Leading zeros? If so, recurse to keep things simple
1078       if (b < e && *b == '0') {
1079         for (++b;; ++b) {
1080           if (b == e) return 0; // just zeros, e.g. "0000"
1081           if (*b != '0') return digits_to<Tgt>(b, e);
1082         }
1083       }
1084       FOLLY_RANGE_CHECK_BEGIN_END(
1085         size == std::numeric_limits<Tgt>::digits10 + 1 &&
1086         strncmp(b, detail::MaxString<Tgt>::value, size) <= 0,
1087         "Numeric overflow upon conversion", b, e);
1088     }
1089
1090     // Here we know that the number won't overflow when
1091     // converted. Proceed without checks.
1092
1093     Tgt result = 0;
1094
1095     for (; e - b >= 4; b += 4) {
1096       result *= 10000;
1097       const int32_t r0 = shift1000[static_cast<size_t>(b[0])];
1098       const int32_t r1 = shift100[static_cast<size_t>(b[1])];
1099       const int32_t r2 = shift10[static_cast<size_t>(b[2])];
1100       const int32_t r3 = shift1[static_cast<size_t>(b[3])];
1101       const auto sum = r0 + r1 + r2 + r3;
1102       assert(sum < OOR && "Assumption: string only has digits");
1103       result += sum;
1104     }
1105
1106     switch (e - b) {
1107       case 3: {
1108         const int32_t r0 = shift100[static_cast<size_t>(b[0])];
1109         const int32_t r1 = shift10[static_cast<size_t>(b[1])];
1110         const int32_t r2 = shift1[static_cast<size_t>(b[2])];
1111         const auto sum = r0 + r1 + r2;
1112         assert(sum < OOR && "Assumption: string only has digits");
1113         return result * 1000 + sum;
1114       }
1115       case 2: {
1116         const int32_t r0 = shift10[static_cast<size_t>(b[0])];
1117         const int32_t r1 = shift1[static_cast<size_t>(b[1])];
1118         const auto sum = r0 + r1;
1119         assert(sum < OOR && "Assumption: string only has digits");
1120         return result * 100 + sum;
1121       }
1122       case 1: {
1123         const int32_t sum = shift1[static_cast<size_t>(b[0])];
1124         assert(sum < OOR && "Assumption: string only has digits");
1125         return result * 10 + sum;
1126       }
1127     }
1128
1129     assert(b == e);
1130     FOLLY_RANGE_CHECK_BEGIN_END(size > 0,
1131                                 "Found no digits to convert in input", b, e);
1132     return result;
1133   }
1134
1135
1136   bool str_to_bool(StringPiece * src);
1137
1138 }                                 // namespace detail
1139
1140 /**
1141  * String represented as a pair of pointers to char to unsigned
1142  * integrals. Assumes NO whitespace before or after.
1143  */
1144 template <class Tgt>
1145 typename std::enable_if<
1146   std::is_integral<Tgt>::value && !std::is_signed<Tgt>::value
1147   && !std::is_same<typename std::remove_cv<Tgt>::type, bool>::value,
1148   Tgt>::type
1149 to(const char * b, const char * e) {
1150   return detail::digits_to<Tgt>(b, e);
1151 }
1152
1153 /**
1154  * String represented as a pair of pointers to char to signed
1155  * integrals. Assumes NO whitespace before or after. Allows an
1156  * optional leading sign.
1157  */
1158 template <class Tgt>
1159 typename std::enable_if<
1160   std::is_integral<Tgt>::value && std::is_signed<Tgt>::value,
1161   Tgt>::type
1162 to(const char * b, const char * e) {
1163   FOLLY_RANGE_CHECK(b < e, "Empty input string in conversion to integral",
1164                     to<std::string>("b: ", intptr_t(b), " e: ", intptr_t(e)));
1165   if (!isdigit(*b)) {
1166     if (*b == '-') {
1167       Tgt result = -to<typename std::make_unsigned<Tgt>::type>(b + 1, e);
1168       FOLLY_RANGE_CHECK_BEGIN_END(result <= 0, "Negative overflow.", b, e);
1169       return result;
1170     }
1171     FOLLY_RANGE_CHECK_BEGIN_END(*b == '+', "Invalid lead character", b, e);
1172     ++b;
1173   }
1174   Tgt result = to<typename std::make_unsigned<Tgt>::type>(b, e);
1175   FOLLY_RANGE_CHECK_BEGIN_END(result >= 0, "Overflow", b, e);
1176   return result;
1177 }
1178
1179 /**
1180  * Parsing strings to integrals. These routines differ from
1181  * to<integral>(string) in that they take a POINTER TO a StringPiece
1182  * and alter that StringPiece to reflect progress information.
1183  */
1184
1185 /**
1186  * StringPiece to integrals, with progress information. Alters the
1187  * StringPiece parameter to munch the already-parsed characters.
1188  */
1189 template <class Tgt>
1190 typename std::enable_if<
1191   std::is_integral<Tgt>::value
1192   && !std::is_same<typename std::remove_cv<Tgt>::type, bool>::value,
1193   Tgt>::type
1194 to(StringPiece * src) {
1195
1196   auto b = src->data(), past = src->data() + src->size();
1197   for (;; ++b) {
1198     FOLLY_RANGE_CHECK_STRINGPIECE(b < past,
1199                                   "No digits found in input string", *src);
1200     if (!isspace(*b)) break;
1201   }
1202
1203   auto m = b;
1204
1205   // First digit is customized because we test for sign
1206   bool negative = false;
1207   /* static */ if (std::is_signed<Tgt>::value) {
1208     if (!isdigit(*m)) {
1209       if (*m == '-') {
1210         negative = true;
1211       } else {
1212         FOLLY_RANGE_CHECK_STRINGPIECE(*m == '+', "Invalid leading character in "
1213                                       "conversion to integral", *src);
1214       }
1215       ++b;
1216       ++m;
1217     }
1218   }
1219   FOLLY_RANGE_CHECK_STRINGPIECE(m < past, "No digits found in input string",
1220                                 *src);
1221   FOLLY_RANGE_CHECK_STRINGPIECE(isdigit(*m), "Non-digit character found", *src);
1222   m = detail::findFirstNonDigit<Tgt>(m + 1, past);
1223
1224   Tgt result;
1225   /* static */ if (!std::is_signed<Tgt>::value) {
1226     result = detail::digits_to<typename std::make_unsigned<Tgt>::type>(b, m);
1227   } else {
1228     auto t = detail::digits_to<typename std::make_unsigned<Tgt>::type>(b, m);
1229     if (negative) {
1230       result = -t;
1231       FOLLY_RANGE_CHECK_STRINGPIECE(is_non_positive(result),
1232                                     "Negative overflow", *src);
1233     } else {
1234       result = t;
1235       FOLLY_RANGE_CHECK_STRINGPIECE(is_non_negative(result), "Overflow", *src);
1236     }
1237   }
1238   src->advance(m - src->data());
1239   return result;
1240 }
1241
1242 /**
1243  * StringPiece to bool, with progress information. Alters the
1244  * StringPiece parameter to munch the already-parsed characters.
1245  */
1246 template <class Tgt>
1247 typename std::enable_if<
1248   std::is_same<typename std::remove_cv<Tgt>::type, bool>::value,
1249   Tgt>::type
1250 to(StringPiece * src) {
1251   return detail::str_to_bool(src);
1252 }
1253
1254 namespace detail {
1255
1256 /**
1257  * Enforce that the suffix following a number is made up only of whitespace.
1258  */
1259 inline void enforceWhitespace(const char* b, const char* e) {
1260   for (; b != e; ++b) {
1261     FOLLY_RANGE_CHECK_BEGIN_END(isspace(*b),
1262                                 to<std::string>("Non-whitespace: ", *b),
1263                                 b, e);
1264   }
1265 }
1266
1267 }  // namespace detail
1268
1269 /**
1270  * String or StringPiece to integrals. Accepts leading and trailing
1271  * whitespace, but no non-space trailing characters.
1272  */
1273 template <class Tgt>
1274 typename std::enable_if<
1275   std::is_integral<Tgt>::value,
1276   Tgt>::type
1277 to(StringPiece src) {
1278   Tgt result = to<Tgt>(&src);
1279   detail::enforceWhitespace(src.data(), src.data() + src.size());
1280   return result;
1281 }
1282
1283 /*******************************************************************************
1284  * Conversions from string types to floating-point types.
1285  ******************************************************************************/
1286
1287 /**
1288  * StringPiece to double, with progress information. Alters the
1289  * StringPiece parameter to munch the already-parsed characters.
1290  */
1291 template <class Tgt>
1292 inline typename std::enable_if<
1293   std::is_floating_point<Tgt>::value,
1294   Tgt>::type
1295 to(StringPiece *const src) {
1296   using namespace double_conversion;
1297   static StringToDoubleConverter
1298     conv(StringToDoubleConverter::ALLOW_TRAILING_JUNK
1299          | StringToDoubleConverter::ALLOW_LEADING_SPACES,
1300          0.0,
1301          // return this for junk input string
1302          std::numeric_limits<double>::quiet_NaN(),
1303          nullptr, nullptr);
1304
1305   FOLLY_RANGE_CHECK_STRINGPIECE(!src->empty(),
1306                                 "No digits found in input string", *src);
1307
1308   int length;
1309   auto result = conv.StringToDouble(src->data(),
1310                                     static_cast<int>(src->size()),
1311                                     &length); // processed char count
1312
1313   if (!std::isnan(result)) {
1314     src->advance(length);
1315     return result;
1316   }
1317
1318   for (;; src->advance(1)) {
1319     if (src->empty()) {
1320       throw std::range_error("Unable to convert an empty string"
1321                              " to a floating point value.");
1322     }
1323     if (!isspace(src->front())) {
1324       break;
1325     }
1326   }
1327
1328   // Was that "inf[inity]"?
1329   if (src->size() >= 3 && toupper((*src)[0]) == 'I'
1330         && toupper((*src)[1]) == 'N' && toupper((*src)[2]) == 'F') {
1331     if (src->size() >= 8 &&
1332         toupper((*src)[3]) == 'I' &&
1333         toupper((*src)[4]) == 'N' &&
1334         toupper((*src)[5]) == 'I' &&
1335         toupper((*src)[6]) == 'T' &&
1336         toupper((*src)[7]) == 'Y') {
1337       src->advance(8);
1338     } else {
1339       src->advance(3);
1340     }
1341     return std::numeric_limits<Tgt>::infinity();
1342   }
1343
1344   // Was that "-inf[inity]"?
1345   if (src->size() >= 4 && toupper((*src)[0]) == '-'
1346       && toupper((*src)[1]) == 'I' && toupper((*src)[2]) == 'N'
1347       && toupper((*src)[3]) == 'F') {
1348     if (src->size() >= 9 &&
1349         toupper((*src)[4]) == 'I' &&
1350         toupper((*src)[5]) == 'N' &&
1351         toupper((*src)[6]) == 'I' &&
1352         toupper((*src)[7]) == 'T' &&
1353         toupper((*src)[8]) == 'Y') {
1354       src->advance(9);
1355     } else {
1356       src->advance(4);
1357     }
1358     return -std::numeric_limits<Tgt>::infinity();
1359   }
1360
1361   // "nan"?
1362   if (src->size() >= 3 && toupper((*src)[0]) == 'N'
1363         && toupper((*src)[1]) == 'A' && toupper((*src)[2]) == 'N') {
1364     src->advance(3);
1365     return std::numeric_limits<Tgt>::quiet_NaN();
1366   }
1367
1368   // "-nan"?
1369   if (src->size() >= 4 &&
1370       toupper((*src)[0]) == '-' &&
1371       toupper((*src)[1]) == 'N' &&
1372       toupper((*src)[2]) == 'A' &&
1373       toupper((*src)[3]) == 'N') {
1374     src->advance(4);
1375     return -std::numeric_limits<Tgt>::quiet_NaN();
1376   }
1377
1378   // All bets are off
1379   throw std::range_error("Unable to convert \"" + src->toString()
1380                          + "\" to a floating point value.");
1381 }
1382
1383 /**
1384  * Any string, const char*, or StringPiece to double.
1385  */
1386 template <class Tgt>
1387 typename std::enable_if<
1388   std::is_floating_point<Tgt>::value,
1389   Tgt>::type
1390 to(StringPiece src) {
1391   Tgt result = to<double>(&src);
1392   detail::enforceWhitespace(src.data(), src.data() + src.size());
1393   return result;
1394 }
1395
1396 /*******************************************************************************
1397  * Integral to floating point and back
1398  ******************************************************************************/
1399
1400 /**
1401  * Checked conversion from integral to flating point and back. The
1402  * result must be convertible back to the source type without loss of
1403  * precision. This seems Draconian but sometimes is what's needed, and
1404  * complements existing routines nicely. For various rounding
1405  * routines, see <math>.
1406  */
1407 template <class Tgt, class Src>
1408 typename std::enable_if<
1409   (std::is_integral<Src>::value && std::is_floating_point<Tgt>::value)
1410   ||
1411   (std::is_floating_point<Src>::value && std::is_integral<Tgt>::value),
1412   Tgt>::type
1413 to(const Src & value) {
1414   Tgt result = value;
1415   auto witness = static_cast<Src>(result);
1416   if (value != witness) {
1417     throw std::range_error(
1418       to<std::string>("to<>: loss of precision when converting ", value,
1419                       " to type ", typeid(Tgt).name()).c_str());
1420   }
1421   return result;
1422 }
1423
1424 /*******************************************************************************
1425  * Enum to anything and back
1426  ******************************************************************************/
1427
1428 #if defined(__clang__) || __GNUC_PREREQ(4, 7)
1429 // std::underlying_type became available by gcc 4.7.0
1430
1431 template <class Tgt, class Src>
1432 typename std::enable_if<
1433   std::is_enum<Src>::value && !std::is_same<Src, Tgt>::value, Tgt>::type
1434 to(const Src & value) {
1435   return to<Tgt>(static_cast<typename std::underlying_type<Src>::type>(value));
1436 }
1437
1438 template <class Tgt, class Src>
1439 typename std::enable_if<
1440   std::is_enum<Tgt>::value && !std::is_same<Src, Tgt>::value, Tgt>::type
1441 to(const Src & value) {
1442   return static_cast<Tgt>(to<typename std::underlying_type<Tgt>::type>(value));
1443 }
1444
1445 #else
1446
1447 template <class Tgt, class Src>
1448 typename std::enable_if<
1449   std::is_enum<Src>::value && !std::is_same<Src, Tgt>::value, Tgt>::type
1450 to(const Src & value) {
1451   /* static */ if (Src(-1) < 0) {
1452     /* static */ if (sizeof(Src) <= sizeof(int)) {
1453       return to<Tgt>(static_cast<int>(value));
1454     } else {
1455       return to<Tgt>(static_cast<long>(value));
1456     }
1457   } else {
1458     /* static */ if (sizeof(Src) <= sizeof(int)) {
1459       return to<Tgt>(static_cast<unsigned int>(value));
1460     } else {
1461       return to<Tgt>(static_cast<unsigned long>(value));
1462     }
1463   }
1464 }
1465
1466 template <class Tgt, class Src>
1467 typename std::enable_if<
1468   std::is_enum<Tgt>::value && !std::is_same<Src, Tgt>::value, Tgt>::type
1469 to(const Src & value) {
1470   /* static */ if (Tgt(-1) < 0) {
1471     /* static */ if (sizeof(Tgt) <= sizeof(int)) {
1472       return static_cast<Tgt>(to<int>(value));
1473     } else {
1474       return static_cast<Tgt>(to<long>(value));
1475     }
1476   } else {
1477     /* static */ if (sizeof(Tgt) <= sizeof(int)) {
1478       return static_cast<Tgt>(to<unsigned int>(value));
1479     } else {
1480       return static_cast<Tgt>(to<unsigned long>(value));
1481     }
1482   }
1483 }
1484
1485 #endif // gcc 4.7 onwards
1486
1487 } // namespace folly
1488
1489 // FOLLY_CONV_INTERNAL is defined by Conv.cpp.  Keep the FOLLY_RANGE_CHECK
1490 // macro for use in Conv.cpp, but #undefine it everywhere else we are included,
1491 // to avoid defining this global macro name in other files that include Conv.h.
1492 #ifndef FOLLY_CONV_INTERNAL
1493 #undef FOLLY_RANGE_CHECK
1494 #undef FOLLY_RANGE_CHECK_BEGIN_END
1495 #undef FOLLY_RANGE_CHECK_STRINGPIECE
1496 #undef FOLLY_RANGE_CHECK_STRINGIZE
1497 #undef FOLLY_RANGE_CHECK_STRINGIZE2
1498 #endif
1499
1500 #endif /* FOLLY_BASE_CONV_H_ */