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