Conv.h 48 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586
  1. /*
  2. * Copyright 2011-present 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. * Converts anything to anything, with an emphasis on performance and
  18. * safety.
  19. *
  20. * @author Andrei Alexandrescu (andrei.alexandrescu@fb.com)
  21. */
  22. #pragma once
  23. #include <algorithm>
  24. #include <cctype>
  25. #include <climits>
  26. #include <cstddef>
  27. #include <limits>
  28. #include <stdexcept>
  29. #include <string>
  30. #include <tuple>
  31. #include <type_traits>
  32. #include <typeinfo>
  33. #include <utility>
  34. #include <double-conversion/double-conversion.h> // V8 JavaScript implementation
  35. #include <folly/Demangle.h>
  36. #include <folly/Expected.h>
  37. #include <folly/FBString.h>
  38. #include <folly/Likely.h>
  39. #include <folly/Range.h>
  40. #include <folly/Traits.h>
  41. #include <folly/Unit.h>
  42. #include <folly/lang/Exception.h>
  43. #include <folly/portability/Math.h>
  44. namespace folly {
  45. // Keep this in sync with kErrorStrings in Conv.cpp
  46. enum class ConversionCode : unsigned char {
  47. SUCCESS,
  48. EMPTY_INPUT_STRING,
  49. NO_DIGITS,
  50. BOOL_OVERFLOW,
  51. BOOL_INVALID_VALUE,
  52. NON_DIGIT_CHAR,
  53. INVALID_LEADING_CHAR,
  54. POSITIVE_OVERFLOW,
  55. NEGATIVE_OVERFLOW,
  56. STRING_TO_FLOAT_ERROR,
  57. NON_WHITESPACE_AFTER_END,
  58. ARITH_POSITIVE_OVERFLOW,
  59. ARITH_NEGATIVE_OVERFLOW,
  60. ARITH_LOSS_OF_PRECISION,
  61. NUM_ERROR_CODES, // has to be the last entry
  62. };
  63. struct ConversionErrorBase : std::range_error {
  64. using std::range_error::range_error;
  65. };
  66. class ConversionError : public ConversionErrorBase {
  67. public:
  68. ConversionError(const std::string& str, ConversionCode code)
  69. : ConversionErrorBase(str), code_(code) {}
  70. ConversionError(const char* str, ConversionCode code)
  71. : ConversionErrorBase(str), code_(code) {}
  72. ConversionCode errorCode() const {
  73. return code_;
  74. }
  75. private:
  76. ConversionCode code_;
  77. };
  78. /*******************************************************************************
  79. * Custom Error Translation
  80. *
  81. * Your overloaded parseTo() function can return a custom error code on failure.
  82. * ::folly::to() will call makeConversionError to translate that error code into
  83. * an object to throw. makeConversionError is found by argument-dependent
  84. * lookup. It should have this signature:
  85. *
  86. * namespace other_namespace {
  87. * enum YourErrorCode { BAD_ERROR, WORSE_ERROR };
  88. *
  89. * struct YourConversionError : ConversionErrorBase {
  90. * YourConversionError(const char* what) : ConversionErrorBase(what) {}
  91. * };
  92. *
  93. * YourConversionError
  94. * makeConversionError(YourErrorCode code, ::folly::StringPiece sp) {
  95. * ...
  96. * return YourConversionError(messageString);
  97. * }
  98. ******************************************************************************/
  99. ConversionError makeConversionError(ConversionCode code, StringPiece sp);
  100. namespace detail {
  101. /**
  102. * Enforce that the suffix following a number is made up only of whitespace.
  103. */
  104. inline ConversionCode enforceWhitespaceErr(StringPiece sp) {
  105. for (auto c : sp) {
  106. if (UNLIKELY(!std::isspace(c))) {
  107. return ConversionCode::NON_WHITESPACE_AFTER_END;
  108. }
  109. }
  110. return ConversionCode::SUCCESS;
  111. }
  112. /**
  113. * Keep this implementation around for prettyToDouble().
  114. */
  115. inline void enforceWhitespace(StringPiece sp) {
  116. auto err = enforceWhitespaceErr(sp);
  117. if (err != ConversionCode::SUCCESS) {
  118. throw_exception(makeConversionError(err, sp));
  119. }
  120. }
  121. } // namespace detail
  122. /**
  123. * The identity conversion function.
  124. * tryTo<T>(T) returns itself for all types T.
  125. */
  126. template <class Tgt, class Src>
  127. typename std::enable_if<
  128. std::is_same<Tgt, typename std::decay<Src>::type>::value,
  129. Expected<Tgt, ConversionCode>>::type
  130. tryTo(Src&& value) {
  131. return std::forward<Src>(value);
  132. }
  133. template <class Tgt, class Src>
  134. typename std::enable_if<
  135. std::is_same<Tgt, typename std::decay<Src>::type>::value,
  136. Tgt>::type
  137. to(Src&& value) {
  138. return std::forward<Src>(value);
  139. }
  140. /*******************************************************************************
  141. * Arithmetic to boolean
  142. ******************************************************************************/
  143. /**
  144. * Unchecked conversion from arithmetic to boolean. This is different from the
  145. * other arithmetic conversions because we use the C convention of treating any
  146. * non-zero value as true, instead of range checking.
  147. */
  148. template <class Tgt, class Src>
  149. typename std::enable_if<
  150. std::is_arithmetic<Src>::value && !std::is_same<Tgt, Src>::value &&
  151. std::is_same<Tgt, bool>::value,
  152. Expected<Tgt, ConversionCode>>::type
  153. tryTo(const Src& value) {
  154. return value != Src();
  155. }
  156. template <class Tgt, class Src>
  157. typename std::enable_if<
  158. std::is_arithmetic<Src>::value && !std::is_same<Tgt, Src>::value &&
  159. std::is_same<Tgt, bool>::value,
  160. Tgt>::type
  161. to(const Src& value) {
  162. return value != Src();
  163. }
  164. /*******************************************************************************
  165. * Anything to string
  166. ******************************************************************************/
  167. namespace detail {
  168. #ifdef _MSC_VER
  169. // MSVC can't quite figure out the LastElementImpl::call() stuff
  170. // in the base implementation, so we have to use tuples instead,
  171. // which result in significantly more templates being compiled,
  172. // though the runtime performance is the same.
  173. template <typename... Ts>
  174. auto getLastElement(Ts&&... ts) -> decltype(std::get<sizeof...(Ts) - 1>(
  175. std::forward_as_tuple(std::forward<Ts>(ts)...))) {
  176. return std::get<sizeof...(Ts) - 1>(
  177. std::forward_as_tuple(std::forward<Ts>(ts)...));
  178. }
  179. inline void getLastElement() {}
  180. template <size_t size, typename... Ts>
  181. struct LastElementType : std::tuple_element<size - 1, std::tuple<Ts...>> {};
  182. template <>
  183. struct LastElementType<0> {
  184. using type = void;
  185. };
  186. template <class... Ts>
  187. struct LastElement
  188. : std::decay<typename LastElementType<sizeof...(Ts), Ts...>::type> {};
  189. #else
  190. template <typename... Ts>
  191. struct LastElementImpl {
  192. static void call(Ignored<Ts>...) {}
  193. };
  194. template <typename Head, typename... Ts>
  195. struct LastElementImpl<Head, Ts...> {
  196. template <typename Last>
  197. static Last call(Ignored<Ts>..., Last&& last) {
  198. return std::forward<Last>(last);
  199. }
  200. };
  201. template <typename... Ts>
  202. auto getLastElement(const Ts&... ts)
  203. -> decltype(LastElementImpl<Ts...>::call(ts...)) {
  204. return LastElementImpl<Ts...>::call(ts...);
  205. }
  206. template <class... Ts>
  207. struct LastElement : std::decay<decltype(
  208. LastElementImpl<Ts...>::call(std::declval<Ts>()...))> {
  209. };
  210. #endif
  211. } // namespace detail
  212. /*******************************************************************************
  213. * Conversions from integral types to string types.
  214. ******************************************************************************/
  215. #if FOLLY_HAVE_INT128_T
  216. namespace detail {
  217. template <typename IntegerType>
  218. constexpr unsigned int digitsEnough() {
  219. return (unsigned int)(ceil(sizeof(IntegerType) * CHAR_BIT * M_LN2 / M_LN10));
  220. }
  221. inline size_t
  222. unsafeTelescope128(char* buffer, size_t room, unsigned __int128 x) {
  223. typedef unsigned __int128 Usrc;
  224. size_t p = room - 1;
  225. while (x >= (Usrc(1) << 64)) { // Using 128-bit division while needed
  226. const auto y = x / 10;
  227. const auto digit = x % 10;
  228. buffer[p--] = static_cast<char>('0' + digit);
  229. x = y;
  230. }
  231. uint64_t xx = static_cast<uint64_t>(x); // Rest uses faster 64-bit division
  232. while (xx >= 10) {
  233. const auto y = xx / 10ULL;
  234. const auto digit = xx % 10ULL;
  235. buffer[p--] = static_cast<char>('0' + digit);
  236. xx = y;
  237. }
  238. buffer[p] = static_cast<char>('0' + xx);
  239. return p;
  240. }
  241. } // namespace detail
  242. #endif
  243. /**
  244. * Returns the number of digits in the base 10 representation of an
  245. * uint64_t. Useful for preallocating buffers and such. It's also used
  246. * internally, see below. Measurements suggest that defining a
  247. * separate overload for 32-bit integers is not worthwhile.
  248. */
  249. inline uint32_t digits10(uint64_t v) {
  250. #ifdef __x86_64__
  251. // For this arch we can get a little help from specialized CPU instructions
  252. // which can count leading zeroes; 64 minus that is appx. log (base 2).
  253. // Use that to approximate base-10 digits (log_10) and then adjust if needed.
  254. // 10^i, defined for i 0 through 19.
  255. // This is 20 * 8 == 160 bytes, which fits neatly into 5 cache lines
  256. // (assuming a cache line size of 64).
  257. alignas(64) static const uint64_t powersOf10[20] = {
  258. 1,
  259. 10,
  260. 100,
  261. 1000,
  262. 10000,
  263. 100000,
  264. 1000000,
  265. 10000000,
  266. 100000000,
  267. 1000000000,
  268. 10000000000,
  269. 100000000000,
  270. 1000000000000,
  271. 10000000000000,
  272. 100000000000000,
  273. 1000000000000000,
  274. 10000000000000000,
  275. 100000000000000000,
  276. 1000000000000000000,
  277. 10000000000000000000UL,
  278. };
  279. // "count leading zeroes" operation not valid; for 0; special case this.
  280. if (UNLIKELY(!v)) {
  281. return 1;
  282. }
  283. // bits is in the ballpark of log_2(v).
  284. const uint32_t leadingZeroes = __builtin_clzll(v);
  285. const auto bits = 63 - leadingZeroes;
  286. // approximate log_10(v) == log_10(2) * bits.
  287. // Integer magic below: 77/256 is appx. 0.3010 (log_10(2)).
  288. // The +1 is to make this the ceiling of the log_10 estimate.
  289. const uint32_t minLength = 1 + ((bits * 77) >> 8);
  290. // return that log_10 lower bound, plus adjust if input >= 10^(that bound)
  291. // in case there's a small error and we misjudged length.
  292. return minLength + uint32_t(v >= powersOf10[minLength]);
  293. #else
  294. uint32_t result = 1;
  295. while (true) {
  296. if (LIKELY(v < 10)) {
  297. return result;
  298. }
  299. if (LIKELY(v < 100)) {
  300. return result + 1;
  301. }
  302. if (LIKELY(v < 1000)) {
  303. return result + 2;
  304. }
  305. if (LIKELY(v < 10000)) {
  306. return result + 3;
  307. }
  308. // Skip ahead by 4 orders of magnitude
  309. v /= 10000U;
  310. result += 4;
  311. }
  312. #endif
  313. }
  314. /**
  315. * Copies the ASCII base 10 representation of v into buffer and
  316. * returns the number of bytes written. Does NOT append a \0. Assumes
  317. * the buffer points to digits10(v) bytes of valid memory. Note that
  318. * uint64 needs at most 20 bytes, uint32_t needs at most 10 bytes,
  319. * uint16_t needs at most 5 bytes, and so on. Measurements suggest
  320. * that defining a separate overload for 32-bit integers is not
  321. * worthwhile.
  322. *
  323. * This primitive is unsafe because it makes the size assumption and
  324. * because it does not add a terminating \0.
  325. */
  326. inline uint32_t uint64ToBufferUnsafe(uint64_t v, char* const buffer) {
  327. auto const result = digits10(v);
  328. // WARNING: using size_t or pointer arithmetic for pos slows down
  329. // the loop below 20x. This is because several 32-bit ops can be
  330. // done in parallel, but only fewer 64-bit ones.
  331. uint32_t pos = result - 1;
  332. while (v >= 10) {
  333. // Keep these together so a peephole optimization "sees" them and
  334. // computes them in one shot.
  335. auto const q = v / 10;
  336. auto const r = v % 10;
  337. buffer[pos--] = static_cast<char>('0' + r);
  338. v = q;
  339. }
  340. // Last digit is trivial to handle
  341. buffer[pos] = static_cast<char>(v + '0');
  342. return result;
  343. }
  344. /**
  345. * A single char gets appended.
  346. */
  347. template <class Tgt>
  348. void toAppend(char value, Tgt* result) {
  349. *result += value;
  350. }
  351. template <class T>
  352. constexpr typename std::enable_if<std::is_same<T, char>::value, size_t>::type
  353. estimateSpaceNeeded(T) {
  354. return 1;
  355. }
  356. template <size_t N>
  357. constexpr size_t estimateSpaceNeeded(const char (&)[N]) {
  358. return N;
  359. }
  360. /**
  361. * Everything implicitly convertible to const char* gets appended.
  362. */
  363. template <class Tgt, class Src>
  364. typename std::enable_if<
  365. std::is_convertible<Src, const char*>::value &&
  366. IsSomeString<Tgt>::value>::type
  367. toAppend(Src value, Tgt* result) {
  368. // Treat null pointers like an empty string, as in:
  369. // operator<<(std::ostream&, const char*).
  370. const char* c = value;
  371. if (c) {
  372. result->append(value);
  373. }
  374. }
  375. template <class Src>
  376. typename std::enable_if<std::is_convertible<Src, const char*>::value, size_t>::
  377. type
  378. estimateSpaceNeeded(Src value) {
  379. const char* c = value;
  380. if (c) {
  381. return folly::StringPiece(value).size();
  382. };
  383. return 0;
  384. }
  385. template <class Src>
  386. typename std::enable_if<IsSomeString<Src>::value, size_t>::type
  387. estimateSpaceNeeded(Src const& value) {
  388. return value.size();
  389. }
  390. template <class Src>
  391. typename std::enable_if<
  392. std::is_convertible<Src, folly::StringPiece>::value &&
  393. !IsSomeString<Src>::value &&
  394. !std::is_convertible<Src, const char*>::value,
  395. size_t>::type
  396. estimateSpaceNeeded(Src value) {
  397. return folly::StringPiece(value).size();
  398. }
  399. template <>
  400. inline size_t estimateSpaceNeeded(std::nullptr_t /* value */) {
  401. return 0;
  402. }
  403. template <class Src>
  404. typename std::enable_if<
  405. std::is_pointer<Src>::value &&
  406. IsSomeString<std::remove_pointer<Src>>::value,
  407. size_t>::type
  408. estimateSpaceNeeded(Src value) {
  409. return value->size();
  410. }
  411. /**
  412. * Strings get appended, too.
  413. */
  414. template <class Tgt, class Src>
  415. typename std::enable_if<
  416. IsSomeString<Src>::value && IsSomeString<Tgt>::value>::type
  417. toAppend(const Src& value, Tgt* result) {
  418. result->append(value);
  419. }
  420. /**
  421. * and StringPiece objects too
  422. */
  423. template <class Tgt>
  424. typename std::enable_if<IsSomeString<Tgt>::value>::type toAppend(
  425. StringPiece value,
  426. Tgt* result) {
  427. result->append(value.data(), value.size());
  428. }
  429. /**
  430. * There's no implicit conversion from fbstring to other string types,
  431. * so make a specialization.
  432. */
  433. template <class Tgt>
  434. typename std::enable_if<IsSomeString<Tgt>::value>::type toAppend(
  435. const fbstring& value,
  436. Tgt* result) {
  437. result->append(value.data(), value.size());
  438. }
  439. #if FOLLY_HAVE_INT128_T
  440. /**
  441. * Special handling for 128 bit integers.
  442. */
  443. template <class Tgt>
  444. void toAppend(__int128 value, Tgt* result) {
  445. typedef unsigned __int128 Usrc;
  446. char buffer[detail::digitsEnough<unsigned __int128>() + 1];
  447. size_t p;
  448. if (value < 0) {
  449. p = detail::unsafeTelescope128(buffer, sizeof(buffer), -Usrc(value));
  450. buffer[--p] = '-';
  451. } else {
  452. p = detail::unsafeTelescope128(buffer, sizeof(buffer), value);
  453. }
  454. result->append(buffer + p, buffer + sizeof(buffer));
  455. }
  456. template <class Tgt>
  457. void toAppend(unsigned __int128 value, Tgt* result) {
  458. char buffer[detail::digitsEnough<unsigned __int128>()];
  459. size_t p;
  460. p = detail::unsafeTelescope128(buffer, sizeof(buffer), value);
  461. result->append(buffer + p, buffer + sizeof(buffer));
  462. }
  463. template <class T>
  464. constexpr
  465. typename std::enable_if<std::is_same<T, __int128>::value, size_t>::type
  466. estimateSpaceNeeded(T) {
  467. return detail::digitsEnough<__int128>();
  468. }
  469. template <class T>
  470. constexpr typename std::
  471. enable_if<std::is_same<T, unsigned __int128>::value, size_t>::type
  472. estimateSpaceNeeded(T) {
  473. return detail::digitsEnough<unsigned __int128>();
  474. }
  475. #endif
  476. /**
  477. * int32_t and int64_t to string (by appending) go through here. The
  478. * result is APPENDED to a preexisting string passed as the second
  479. * parameter. This should be efficient with fbstring because fbstring
  480. * incurs no dynamic allocation below 23 bytes and no number has more
  481. * than 22 bytes in its textual representation (20 for digits, one for
  482. * sign, one for the terminating 0).
  483. */
  484. template <class Tgt, class Src>
  485. typename std::enable_if<
  486. std::is_integral<Src>::value && std::is_signed<Src>::value &&
  487. IsSomeString<Tgt>::value && sizeof(Src) >= 4>::type
  488. toAppend(Src value, Tgt* result) {
  489. char buffer[20];
  490. if (value < 0) {
  491. result->push_back('-');
  492. result->append(
  493. buffer,
  494. uint64ToBufferUnsafe(~static_cast<uint64_t>(value) + 1, buffer));
  495. } else {
  496. result->append(buffer, uint64ToBufferUnsafe(uint64_t(value), buffer));
  497. }
  498. }
  499. template <class Src>
  500. typename std::enable_if<
  501. std::is_integral<Src>::value && std::is_signed<Src>::value &&
  502. sizeof(Src) >= 4 && sizeof(Src) < 16,
  503. size_t>::type
  504. estimateSpaceNeeded(Src value) {
  505. if (value < 0) {
  506. // When "value" is the smallest negative, negating it would evoke
  507. // undefined behavior, so, instead of writing "-value" below, we write
  508. // "~static_cast<uint64_t>(value) + 1"
  509. return 1 + digits10(~static_cast<uint64_t>(value) + 1);
  510. }
  511. return digits10(static_cast<uint64_t>(value));
  512. }
  513. /**
  514. * As above, but for uint32_t and uint64_t.
  515. */
  516. template <class Tgt, class Src>
  517. typename std::enable_if<
  518. std::is_integral<Src>::value && !std::is_signed<Src>::value &&
  519. IsSomeString<Tgt>::value && sizeof(Src) >= 4>::type
  520. toAppend(Src value, Tgt* result) {
  521. char buffer[20];
  522. result->append(buffer, uint64ToBufferUnsafe(value, buffer));
  523. }
  524. template <class Src>
  525. typename std::enable_if<
  526. std::is_integral<Src>::value && !std::is_signed<Src>::value &&
  527. sizeof(Src) >= 4 && sizeof(Src) < 16,
  528. size_t>::type
  529. estimateSpaceNeeded(Src value) {
  530. return digits10(value);
  531. }
  532. /**
  533. * All small signed and unsigned integers to string go through 32-bit
  534. * types int32_t and uint32_t, respectively.
  535. */
  536. template <class Tgt, class Src>
  537. typename std::enable_if<
  538. std::is_integral<Src>::value && IsSomeString<Tgt>::value &&
  539. sizeof(Src) < 4>::type
  540. toAppend(Src value, Tgt* result) {
  541. typedef
  542. typename std::conditional<std::is_signed<Src>::value, int64_t, uint64_t>::
  543. type Intermediate;
  544. toAppend<Tgt>(static_cast<Intermediate>(value), result);
  545. }
  546. template <class Src>
  547. typename std::enable_if<
  548. std::is_integral<Src>::value && sizeof(Src) < 4 &&
  549. !std::is_same<Src, char>::value,
  550. size_t>::type
  551. estimateSpaceNeeded(Src value) {
  552. typedef
  553. typename std::conditional<std::is_signed<Src>::value, int64_t, uint64_t>::
  554. type Intermediate;
  555. return estimateSpaceNeeded(static_cast<Intermediate>(value));
  556. }
  557. /**
  558. * Enumerated values get appended as integers.
  559. */
  560. template <class Tgt, class Src>
  561. typename std::enable_if<
  562. std::is_enum<Src>::value && IsSomeString<Tgt>::value>::type
  563. toAppend(Src value, Tgt* result) {
  564. toAppend(
  565. static_cast<typename std::underlying_type<Src>::type>(value), result);
  566. }
  567. template <class Src>
  568. typename std::enable_if<std::is_enum<Src>::value, size_t>::type
  569. estimateSpaceNeeded(Src value) {
  570. return estimateSpaceNeeded(
  571. static_cast<typename std::underlying_type<Src>::type>(value));
  572. }
  573. /*******************************************************************************
  574. * Conversions from floating-point types to string types.
  575. ******************************************************************************/
  576. namespace detail {
  577. constexpr int kConvMaxDecimalInShortestLow = -6;
  578. constexpr int kConvMaxDecimalInShortestHigh = 21;
  579. } // namespace detail
  580. /** Wrapper around DoubleToStringConverter **/
  581. template <class Tgt, class Src>
  582. typename std::enable_if<
  583. std::is_floating_point<Src>::value && 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 conv(
  591. DoubleToStringConverter::NO_FLAGS,
  592. "Infinity",
  593. "NaN",
  594. 'E',
  595. detail::kConvMaxDecimalInShortestLow,
  596. detail::kConvMaxDecimalInShortestHigh,
  597. 6, // max leading padding zeros
  598. 1); // max trailing padding zeros
  599. char buffer[256];
  600. StringBuilder builder(buffer, sizeof(buffer));
  601. switch (mode) {
  602. case DoubleToStringConverter::SHORTEST:
  603. conv.ToShortest(value, &builder);
  604. break;
  605. case DoubleToStringConverter::SHORTEST_SINGLE:
  606. conv.ToShortestSingle(static_cast<float>(value), &builder);
  607. break;
  608. case DoubleToStringConverter::FIXED:
  609. conv.ToFixed(value, int(numDigits), &builder);
  610. break;
  611. default:
  612. CHECK(mode == DoubleToStringConverter::PRECISION);
  613. conv.ToPrecision(value, int(numDigits), &builder);
  614. break;
  615. }
  616. const size_t length = size_t(builder.position());
  617. builder.Finalize();
  618. result->append(buffer, length);
  619. }
  620. /**
  621. * As above, but for floating point
  622. */
  623. template <class Tgt, class Src>
  624. typename std::enable_if<
  625. std::is_floating_point<Src>::value && IsSomeString<Tgt>::value>::type
  626. toAppend(Src value, Tgt* result) {
  627. toAppend(
  628. value, result, double_conversion::DoubleToStringConverter::SHORTEST, 0);
  629. }
  630. /**
  631. * Upper bound of the length of the output from
  632. * DoubleToStringConverter::ToShortest(double, StringBuilder*),
  633. * as used in toAppend(double, string*).
  634. */
  635. template <class Src>
  636. typename std::enable_if<std::is_floating_point<Src>::value, size_t>::type
  637. estimateSpaceNeeded(Src value) {
  638. // kBase10MaximalLength is 17. We add 1 for decimal point,
  639. // e.g. 10.0/9 is 17 digits and 18 characters, including the decimal point.
  640. constexpr int kMaxMantissaSpace =
  641. double_conversion::DoubleToStringConverter::kBase10MaximalLength + 1;
  642. // strlen("E-") + digits10(numeric_limits<double>::max_exponent10)
  643. constexpr int kMaxExponentSpace = 2 + 3;
  644. static const int kMaxPositiveSpace = std::max({
  645. // E.g. 1.1111111111111111E-100.
  646. kMaxMantissaSpace + kMaxExponentSpace,
  647. // E.g. 0.000001.1111111111111111, if kConvMaxDecimalInShortestLow is -6.
  648. kMaxMantissaSpace - detail::kConvMaxDecimalInShortestLow,
  649. // If kConvMaxDecimalInShortestHigh is 21, then 1e21 is the smallest
  650. // number > 1 which ToShortest outputs in exponential notation,
  651. // so 21 is the longest non-exponential number > 1.
  652. detail::kConvMaxDecimalInShortestHigh,
  653. });
  654. return size_t(
  655. kMaxPositiveSpace +
  656. (value < 0 ? 1 : 0)); // +1 for minus sign, if negative
  657. }
  658. /**
  659. * This can be specialized, together with adding specialization
  660. * for estimateSpaceNeed for your type, so that we allocate
  661. * as much as you need instead of the default
  662. */
  663. template <class Src>
  664. struct HasLengthEstimator : std::false_type {};
  665. template <class Src>
  666. constexpr typename std::enable_if<
  667. !std::is_fundamental<Src>::value &&
  668. #if FOLLY_HAVE_INT128_T
  669. // On OSX 10.10, is_fundamental<__int128> is false :-O
  670. !std::is_same<__int128, Src>::value &&
  671. !std::is_same<unsigned __int128, Src>::value &&
  672. #endif
  673. !IsSomeString<Src>::value &&
  674. !std::is_convertible<Src, const char*>::value &&
  675. !std::is_convertible<Src, StringPiece>::value &&
  676. !std::is_enum<Src>::value && !HasLengthEstimator<Src>::value,
  677. size_t>::type
  678. estimateSpaceNeeded(const Src&) {
  679. return sizeof(Src) + 1; // dumbest best effort ever?
  680. }
  681. namespace detail {
  682. template <class Tgt>
  683. typename std::enable_if<IsSomeString<Tgt>::value, size_t>::type
  684. estimateSpaceToReserve(size_t sofar, Tgt*) {
  685. return sofar;
  686. }
  687. template <class T, class... Ts>
  688. size_t estimateSpaceToReserve(size_t sofar, const T& v, const Ts&... vs) {
  689. return estimateSpaceToReserve(sofar + estimateSpaceNeeded(v), vs...);
  690. }
  691. template <class... Ts>
  692. void reserveInTarget(const Ts&... vs) {
  693. getLastElement(vs...)->reserve(estimateSpaceToReserve(0, vs...));
  694. }
  695. template <class Delimiter, class... Ts>
  696. void reserveInTargetDelim(const Delimiter& d, const Ts&... vs) {
  697. static_assert(sizeof...(vs) >= 2, "Needs at least 2 args");
  698. size_t fordelim = (sizeof...(vs) - 2) *
  699. estimateSpaceToReserve(0, d, static_cast<std::string*>(nullptr));
  700. getLastElement(vs...)->reserve(estimateSpaceToReserve(fordelim, vs...));
  701. }
  702. /**
  703. * Variadic base case: append one element
  704. */
  705. template <class T, class Tgt>
  706. typename std::enable_if<
  707. IsSomeString<typename std::remove_pointer<Tgt>::type>::value>::type
  708. toAppendStrImpl(const T& v, Tgt result) {
  709. toAppend(v, result);
  710. }
  711. template <class T, class... Ts>
  712. typename std::enable_if<
  713. sizeof...(Ts) >= 2 &&
  714. IsSomeString<typename std::remove_pointer<
  715. typename detail::LastElement<const Ts&...>::type>::type>::value>::type
  716. toAppendStrImpl(const T& v, const Ts&... vs) {
  717. toAppend(v, getLastElement(vs...));
  718. toAppendStrImpl(vs...);
  719. }
  720. template <class Delimiter, class T, class Tgt>
  721. typename std::enable_if<
  722. IsSomeString<typename std::remove_pointer<Tgt>::type>::value>::type
  723. toAppendDelimStrImpl(const Delimiter& /* delim */, const T& v, Tgt result) {
  724. toAppend(v, result);
  725. }
  726. template <class Delimiter, class T, class... Ts>
  727. typename std::enable_if<
  728. sizeof...(Ts) >= 2 &&
  729. IsSomeString<typename std::remove_pointer<
  730. typename detail::LastElement<const Ts&...>::type>::type>::value>::type
  731. toAppendDelimStrImpl(const Delimiter& delim, const T& v, const Ts&... vs) {
  732. // we are really careful here, calling toAppend with just one element does
  733. // not try to estimate space needed (as we already did that). If we call
  734. // toAppend(v, delim, ....) we would do unnecesary size calculation
  735. toAppend(v, detail::getLastElement(vs...));
  736. toAppend(delim, detail::getLastElement(vs...));
  737. toAppendDelimStrImpl(delim, vs...);
  738. }
  739. } // namespace detail
  740. /**
  741. * Variadic conversion to string. Appends each element in turn.
  742. * If we have two or more things to append, we will not reserve
  743. * the space for them and will depend on strings exponential growth.
  744. * If you just append once consider using toAppendFit which reserves
  745. * the space needed (but does not have exponential as a result).
  746. *
  747. * Custom implementations of toAppend() can be provided in the same namespace as
  748. * the type to customize printing. estimateSpaceNeed() may also be provided to
  749. * avoid reallocations in toAppendFit():
  750. *
  751. * namespace other_namespace {
  752. *
  753. * template <class String>
  754. * void toAppend(const OtherType&, String* out);
  755. *
  756. * // optional
  757. * size_t estimateSpaceNeeded(const OtherType&);
  758. *
  759. * }
  760. */
  761. template <class... Ts>
  762. typename std::enable_if<
  763. sizeof...(Ts) >= 3 &&
  764. IsSomeString<typename std::remove_pointer<
  765. typename detail::LastElement<const Ts&...>::type>::type>::value>::type
  766. toAppend(const Ts&... vs) {
  767. ::folly::detail::toAppendStrImpl(vs...);
  768. }
  769. #ifdef _MSC_VER
  770. // Special case pid_t on MSVC, because it's a void* rather than an
  771. // integral type. We can't do a global special case because this is already
  772. // dangerous enough (as most pointers will implicitly convert to a void*)
  773. // just doing it for MSVC.
  774. template <class Tgt>
  775. void toAppend(const pid_t a, Tgt* res) {
  776. toAppend(uint64_t(a), res);
  777. }
  778. #endif
  779. /**
  780. * Special version of the call that preallocates exaclty as much memory
  781. * as need for arguments to be stored in target. This means we are
  782. * not doing exponential growth when we append. If you are using it
  783. * in a loop you are aiming at your foot with a big perf-destroying
  784. * bazooka.
  785. * On the other hand if you are appending to a string once, this
  786. * will probably save a few calls to malloc.
  787. */
  788. template <class... Ts>
  789. typename std::enable_if<IsSomeString<typename std::remove_pointer<
  790. typename detail::LastElement<const Ts&...>::type>::type>::value>::type
  791. toAppendFit(const Ts&... vs) {
  792. ::folly::detail::reserveInTarget(vs...);
  793. toAppend(vs...);
  794. }
  795. template <class Ts>
  796. void toAppendFit(const Ts&) {}
  797. /**
  798. * Variadic base case: do nothing.
  799. */
  800. template <class Tgt>
  801. typename std::enable_if<IsSomeString<Tgt>::value>::type toAppend(
  802. Tgt* /* result */) {}
  803. /**
  804. * Variadic base case: do nothing.
  805. */
  806. template <class Delimiter, class Tgt>
  807. typename std::enable_if<IsSomeString<Tgt>::value>::type toAppendDelim(
  808. const Delimiter& /* delim */,
  809. Tgt* /* result */) {}
  810. /**
  811. * 1 element: same as toAppend.
  812. */
  813. template <class Delimiter, class T, class Tgt>
  814. typename std::enable_if<IsSomeString<Tgt>::value>::type
  815. toAppendDelim(const Delimiter& /* delim */, const T& v, Tgt* tgt) {
  816. toAppend(v, tgt);
  817. }
  818. /**
  819. * Append to string with a delimiter in between elements. Check out
  820. * comments for toAppend for details about memory allocation.
  821. */
  822. template <class Delimiter, class... Ts>
  823. typename std::enable_if<
  824. sizeof...(Ts) >= 3 &&
  825. IsSomeString<typename std::remove_pointer<
  826. typename detail::LastElement<const Ts&...>::type>::type>::value>::type
  827. toAppendDelim(const Delimiter& delim, const Ts&... vs) {
  828. detail::toAppendDelimStrImpl(delim, vs...);
  829. }
  830. /**
  831. * Detail in comment for toAppendFit
  832. */
  833. template <class Delimiter, class... Ts>
  834. typename std::enable_if<IsSomeString<typename std::remove_pointer<
  835. typename detail::LastElement<const Ts&...>::type>::type>::value>::type
  836. toAppendDelimFit(const Delimiter& delim, const Ts&... vs) {
  837. detail::reserveInTargetDelim(delim, vs...);
  838. toAppendDelim(delim, vs...);
  839. }
  840. template <class De, class Ts>
  841. void toAppendDelimFit(const De&, const Ts&) {}
  842. /**
  843. * to<SomeString>(v1, v2, ...) uses toAppend() (see below) as back-end
  844. * for all types.
  845. */
  846. template <class Tgt, class... Ts>
  847. typename std::enable_if<
  848. IsSomeString<Tgt>::value &&
  849. (sizeof...(Ts) != 1 ||
  850. !std::is_same<Tgt, typename detail::LastElement<const Ts&...>::type>::
  851. value),
  852. Tgt>::type
  853. to(const Ts&... vs) {
  854. Tgt result;
  855. toAppendFit(vs..., &result);
  856. return result;
  857. }
  858. /**
  859. * Special version of to<SomeString> for floating point. When calling
  860. * folly::to<SomeString>(double), generic implementation above will
  861. * firstly reserve 24 (or 25 when negative value) bytes. This will
  862. * introduce a malloc call for most mainstream string implementations.
  863. *
  864. * But for most cases, a floating point doesn't need 24 (or 25) bytes to
  865. * be converted as a string.
  866. *
  867. * This special version will not do string reserve.
  868. */
  869. template <class Tgt, class Src>
  870. typename std::enable_if<
  871. IsSomeString<Tgt>::value && std::is_floating_point<Src>::value,
  872. Tgt>::type
  873. to(Src value) {
  874. Tgt result;
  875. toAppend(value, &result);
  876. return result;
  877. }
  878. /**
  879. * toDelim<SomeString>(SomeString str) returns itself.
  880. */
  881. template <class Tgt, class Delim, class Src>
  882. typename std::enable_if<
  883. IsSomeString<Tgt>::value &&
  884. std::is_same<Tgt, typename std::decay<Src>::type>::value,
  885. Tgt>::type
  886. toDelim(const Delim& /* delim */, Src&& value) {
  887. return std::forward<Src>(value);
  888. }
  889. /**
  890. * toDelim<SomeString>(delim, v1, v2, ...) uses toAppendDelim() as
  891. * back-end for all types.
  892. */
  893. template <class Tgt, class Delim, class... Ts>
  894. typename std::enable_if<
  895. IsSomeString<Tgt>::value &&
  896. (sizeof...(Ts) != 1 ||
  897. !std::is_same<Tgt, typename detail::LastElement<const Ts&...>::type>::
  898. value),
  899. Tgt>::type
  900. toDelim(const Delim& delim, const Ts&... vs) {
  901. Tgt result;
  902. toAppendDelimFit(delim, vs..., &result);
  903. return result;
  904. }
  905. /*******************************************************************************
  906. * Conversions from string types to integral types.
  907. ******************************************************************************/
  908. namespace detail {
  909. Expected<bool, ConversionCode> str_to_bool(StringPiece* src) noexcept;
  910. template <typename T>
  911. Expected<T, ConversionCode> str_to_floating(StringPiece* src) noexcept;
  912. extern template Expected<float, ConversionCode> str_to_floating<float>(
  913. StringPiece* src) noexcept;
  914. extern template Expected<double, ConversionCode> str_to_floating<double>(
  915. StringPiece* src) noexcept;
  916. template <class Tgt>
  917. Expected<Tgt, ConversionCode> digits_to(const char* b, const char* e) noexcept;
  918. extern template Expected<char, ConversionCode> digits_to<char>(
  919. const char*,
  920. const char*) noexcept;
  921. extern template Expected<signed char, ConversionCode> digits_to<signed char>(
  922. const char*,
  923. const char*) noexcept;
  924. extern template Expected<unsigned char, ConversionCode>
  925. digits_to<unsigned char>(const char*, const char*) noexcept;
  926. extern template Expected<short, ConversionCode> digits_to<short>(
  927. const char*,
  928. const char*) noexcept;
  929. extern template Expected<unsigned short, ConversionCode>
  930. digits_to<unsigned short>(const char*, const char*) noexcept;
  931. extern template Expected<int, ConversionCode> digits_to<int>(
  932. const char*,
  933. const char*) noexcept;
  934. extern template Expected<unsigned int, ConversionCode> digits_to<unsigned int>(
  935. const char*,
  936. const char*) noexcept;
  937. extern template Expected<long, ConversionCode> digits_to<long>(
  938. const char*,
  939. const char*) noexcept;
  940. extern template Expected<unsigned long, ConversionCode>
  941. digits_to<unsigned long>(const char*, const char*) noexcept;
  942. extern template Expected<long long, ConversionCode> digits_to<long long>(
  943. const char*,
  944. const char*) noexcept;
  945. extern template Expected<unsigned long long, ConversionCode>
  946. digits_to<unsigned long long>(const char*, const char*) noexcept;
  947. #if FOLLY_HAVE_INT128_T
  948. extern template Expected<__int128, ConversionCode> digits_to<__int128>(
  949. const char*,
  950. const char*) noexcept;
  951. extern template Expected<unsigned __int128, ConversionCode>
  952. digits_to<unsigned __int128>(const char*, const char*) noexcept;
  953. #endif
  954. template <class T>
  955. Expected<T, ConversionCode> str_to_integral(StringPiece* src) noexcept;
  956. extern template Expected<char, ConversionCode> str_to_integral<char>(
  957. StringPiece* src) noexcept;
  958. extern template Expected<signed char, ConversionCode>
  959. str_to_integral<signed char>(StringPiece* src) noexcept;
  960. extern template Expected<unsigned char, ConversionCode>
  961. str_to_integral<unsigned char>(StringPiece* src) noexcept;
  962. extern template Expected<short, ConversionCode> str_to_integral<short>(
  963. StringPiece* src) noexcept;
  964. extern template Expected<unsigned short, ConversionCode>
  965. str_to_integral<unsigned short>(StringPiece* src) noexcept;
  966. extern template Expected<int, ConversionCode> str_to_integral<int>(
  967. StringPiece* src) noexcept;
  968. extern template Expected<unsigned int, ConversionCode>
  969. str_to_integral<unsigned int>(StringPiece* src) noexcept;
  970. extern template Expected<long, ConversionCode> str_to_integral<long>(
  971. StringPiece* src) noexcept;
  972. extern template Expected<unsigned long, ConversionCode>
  973. str_to_integral<unsigned long>(StringPiece* src) noexcept;
  974. extern template Expected<long long, ConversionCode> str_to_integral<long long>(
  975. StringPiece* src) noexcept;
  976. extern template Expected<unsigned long long, ConversionCode>
  977. str_to_integral<unsigned long long>(StringPiece* src) noexcept;
  978. #if FOLLY_HAVE_INT128_T
  979. extern template Expected<__int128, ConversionCode> str_to_integral<__int128>(
  980. StringPiece* src) noexcept;
  981. extern template Expected<unsigned __int128, ConversionCode>
  982. str_to_integral<unsigned __int128>(StringPiece* src) noexcept;
  983. #endif
  984. template <typename T>
  985. typename std::
  986. enable_if<std::is_same<T, bool>::value, Expected<T, ConversionCode>>::type
  987. convertTo(StringPiece* src) noexcept {
  988. return str_to_bool(src);
  989. }
  990. template <typename T>
  991. typename std::enable_if<
  992. std::is_floating_point<T>::value,
  993. Expected<T, ConversionCode>>::type
  994. convertTo(StringPiece* src) noexcept {
  995. return str_to_floating<T>(src);
  996. }
  997. template <typename T>
  998. typename std::enable_if<
  999. std::is_integral<T>::value && !std::is_same<T, bool>::value,
  1000. Expected<T, ConversionCode>>::type
  1001. convertTo(StringPiece* src) noexcept {
  1002. return str_to_integral<T>(src);
  1003. }
  1004. } // namespace detail
  1005. /**
  1006. * String represented as a pair of pointers to char to unsigned
  1007. * integrals. Assumes NO whitespace before or after.
  1008. */
  1009. template <typename Tgt>
  1010. typename std::enable_if<
  1011. std::is_integral<Tgt>::value && !std::is_same<Tgt, bool>::value,
  1012. Expected<Tgt, ConversionCode>>::type
  1013. tryTo(const char* b, const char* e) {
  1014. return detail::digits_to<Tgt>(b, e);
  1015. }
  1016. template <typename Tgt>
  1017. typename std::enable_if<
  1018. std::is_integral<Tgt>::value && !std::is_same<Tgt, bool>::value,
  1019. Tgt>::type
  1020. to(const char* b, const char* e) {
  1021. return tryTo<Tgt>(b, e).thenOrThrow(
  1022. [](Tgt res) { return res; },
  1023. [=](ConversionCode code) {
  1024. return makeConversionError(code, StringPiece(b, e));
  1025. });
  1026. }
  1027. /*******************************************************************************
  1028. * Conversions from string types to arithmetic types.
  1029. ******************************************************************************/
  1030. /**
  1031. * Parsing strings to numeric types.
  1032. */
  1033. template <typename Tgt>
  1034. FOLLY_NODISCARD inline typename std::enable_if<
  1035. std::is_arithmetic<Tgt>::value,
  1036. Expected<StringPiece, ConversionCode>>::type
  1037. parseTo(StringPiece src, Tgt& out) {
  1038. return detail::convertTo<Tgt>(&src).then(
  1039. [&](Tgt res) { return void(out = res), src; });
  1040. }
  1041. /*******************************************************************************
  1042. * Integral / Floating Point to integral / Floating Point
  1043. ******************************************************************************/
  1044. namespace detail {
  1045. /**
  1046. * Bool to integral/float doesn't need any special checks, and this
  1047. * overload means we aren't trying to see if a bool is less than
  1048. * an integer.
  1049. */
  1050. template <class Tgt>
  1051. typename std::enable_if<
  1052. !std::is_same<Tgt, bool>::value &&
  1053. (std::is_integral<Tgt>::value || std::is_floating_point<Tgt>::value),
  1054. Expected<Tgt, ConversionCode>>::type
  1055. convertTo(const bool& value) noexcept {
  1056. return static_cast<Tgt>(value ? 1 : 0);
  1057. }
  1058. /**
  1059. * Checked conversion from integral to integral. The checks are only
  1060. * performed when meaningful, e.g. conversion from int to long goes
  1061. * unchecked.
  1062. */
  1063. template <class Tgt, class Src>
  1064. typename std::enable_if<
  1065. std::is_integral<Src>::value && !std::is_same<Tgt, Src>::value &&
  1066. !std::is_same<Tgt, bool>::value && std::is_integral<Tgt>::value,
  1067. Expected<Tgt, ConversionCode>>::type
  1068. convertTo(const Src& value) noexcept {
  1069. if /* constexpr */ (
  1070. folly::_t<std::make_unsigned<Tgt>>(std::numeric_limits<Tgt>::max()) <
  1071. folly::_t<std::make_unsigned<Src>>(std::numeric_limits<Src>::max())) {
  1072. if (greater_than<Tgt, std::numeric_limits<Tgt>::max()>(value)) {
  1073. return makeUnexpected(ConversionCode::ARITH_POSITIVE_OVERFLOW);
  1074. }
  1075. }
  1076. if /* constexpr */ (
  1077. std::is_signed<Src>::value &&
  1078. (!std::is_signed<Tgt>::value || sizeof(Src) > sizeof(Tgt))) {
  1079. if (less_than<Tgt, std::numeric_limits<Tgt>::min()>(value)) {
  1080. return makeUnexpected(ConversionCode::ARITH_NEGATIVE_OVERFLOW);
  1081. }
  1082. }
  1083. return static_cast<Tgt>(value);
  1084. }
  1085. /**
  1086. * Checked conversion from floating to floating. The checks are only
  1087. * performed when meaningful, e.g. conversion from float to double goes
  1088. * unchecked.
  1089. */
  1090. template <class Tgt, class Src>
  1091. typename std::enable_if<
  1092. std::is_floating_point<Tgt>::value && std::is_floating_point<Src>::value &&
  1093. !std::is_same<Tgt, Src>::value,
  1094. Expected<Tgt, ConversionCode>>::type
  1095. convertTo(const Src& value) noexcept {
  1096. if /* constexpr */ (
  1097. std::numeric_limits<Tgt>::max() < std::numeric_limits<Src>::max()) {
  1098. if (value > std::numeric_limits<Tgt>::max()) {
  1099. return makeUnexpected(ConversionCode::ARITH_POSITIVE_OVERFLOW);
  1100. }
  1101. if (value < std::numeric_limits<Tgt>::lowest()) {
  1102. return makeUnexpected(ConversionCode::ARITH_NEGATIVE_OVERFLOW);
  1103. }
  1104. }
  1105. return static_cast<Tgt>(value);
  1106. }
  1107. /**
  1108. * Check if a floating point value can safely be converted to an
  1109. * integer value without triggering undefined behaviour.
  1110. */
  1111. template <typename Tgt, typename Src>
  1112. inline typename std::enable_if<
  1113. std::is_floating_point<Src>::value && std::is_integral<Tgt>::value &&
  1114. !std::is_same<Tgt, bool>::value,
  1115. bool>::type
  1116. checkConversion(const Src& value) {
  1117. constexpr Src tgtMaxAsSrc = static_cast<Src>(std::numeric_limits<Tgt>::max());
  1118. constexpr Src tgtMinAsSrc = static_cast<Src>(std::numeric_limits<Tgt>::min());
  1119. if (value >= tgtMaxAsSrc) {
  1120. if (value > tgtMaxAsSrc) {
  1121. return false;
  1122. }
  1123. const Src mmax = folly::nextafter(tgtMaxAsSrc, Src());
  1124. if (static_cast<Tgt>(value - mmax) >
  1125. std::numeric_limits<Tgt>::max() - static_cast<Tgt>(mmax)) {
  1126. return false;
  1127. }
  1128. } else if (std::is_signed<Tgt>::value && value <= tgtMinAsSrc) {
  1129. if (value < tgtMinAsSrc) {
  1130. return false;
  1131. }
  1132. const Src mmin = folly::nextafter(tgtMinAsSrc, Src());
  1133. if (static_cast<Tgt>(value - mmin) <
  1134. std::numeric_limits<Tgt>::min() - static_cast<Tgt>(mmin)) {
  1135. return false;
  1136. }
  1137. }
  1138. return true;
  1139. }
  1140. // Integers can always safely be converted to floating point values
  1141. template <typename Tgt, typename Src>
  1142. constexpr typename std::enable_if<
  1143. std::is_integral<Src>::value && std::is_floating_point<Tgt>::value,
  1144. bool>::type
  1145. checkConversion(const Src&) {
  1146. return true;
  1147. }
  1148. // Also, floating point values can always be safely converted to bool
  1149. // Per the standard, any floating point value that is not zero will yield true
  1150. template <typename Tgt, typename Src>
  1151. constexpr typename std::enable_if<
  1152. std::is_floating_point<Src>::value && std::is_same<Tgt, bool>::value,
  1153. bool>::type
  1154. checkConversion(const Src&) {
  1155. return true;
  1156. }
  1157. /**
  1158. * Checked conversion from integral to floating point and back. The
  1159. * result must be convertible back to the source type without loss of
  1160. * precision. This seems Draconian but sometimes is what's needed, and
  1161. * complements existing routines nicely. For various rounding
  1162. * routines, see <math>.
  1163. */
  1164. template <typename Tgt, typename Src>
  1165. typename std::enable_if<
  1166. (std::is_integral<Src>::value && std::is_floating_point<Tgt>::value) ||
  1167. (std::is_floating_point<Src>::value && std::is_integral<Tgt>::value),
  1168. Expected<Tgt, ConversionCode>>::type
  1169. convertTo(const Src& value) noexcept {
  1170. if (LIKELY(checkConversion<Tgt>(value))) {
  1171. Tgt result = static_cast<Tgt>(value);
  1172. if (LIKELY(checkConversion<Src>(result))) {
  1173. Src witness = static_cast<Src>(result);
  1174. if (LIKELY(value == witness)) {
  1175. return result;
  1176. }
  1177. }
  1178. }
  1179. return makeUnexpected(ConversionCode::ARITH_LOSS_OF_PRECISION);
  1180. }
  1181. template <typename Tgt, typename Src>
  1182. inline std::string errorValue(const Src& value) {
  1183. #ifdef FOLLY_HAS_RTTI
  1184. return to<std::string>("(", demangle(typeid(Tgt)), ") ", value);
  1185. #else
  1186. return to<std::string>(value);
  1187. #endif
  1188. }
  1189. template <typename Tgt, typename Src>
  1190. using IsArithToArith = bool_constant<
  1191. !std::is_same<Tgt, Src>::value && !std::is_same<Tgt, bool>::value &&
  1192. std::is_arithmetic<Src>::value && std::is_arithmetic<Tgt>::value>;
  1193. } // namespace detail
  1194. template <typename Tgt, typename Src>
  1195. typename std::enable_if<
  1196. detail::IsArithToArith<Tgt, Src>::value,
  1197. Expected<Tgt, ConversionCode>>::type
  1198. tryTo(const Src& value) noexcept {
  1199. return detail::convertTo<Tgt>(value);
  1200. }
  1201. template <typename Tgt, typename Src>
  1202. typename std::enable_if<detail::IsArithToArith<Tgt, Src>::value, Tgt>::type to(
  1203. const Src& value) {
  1204. return tryTo<Tgt>(value).thenOrThrow(
  1205. [](Tgt res) { return res; },
  1206. [&](ConversionCode e) {
  1207. return makeConversionError(e, detail::errorValue<Tgt>(value));
  1208. });
  1209. }
  1210. /*******************************************************************************
  1211. * Custom Conversions
  1212. *
  1213. * Any type can be used with folly::to by implementing parseTo. The
  1214. * implementation should be provided in the namespace of the type to facilitate
  1215. * argument-dependent lookup:
  1216. *
  1217. * namespace other_namespace {
  1218. * ::folly::Expected<::folly::StringPiece, SomeErrorCode>
  1219. * parseTo(::folly::StringPiece, OtherType&) noexcept;
  1220. * }
  1221. ******************************************************************************/
  1222. template <class T>
  1223. FOLLY_NODISCARD typename std::enable_if<
  1224. std::is_enum<T>::value,
  1225. Expected<StringPiece, ConversionCode>>::type
  1226. parseTo(StringPiece in, T& out) noexcept {
  1227. typename std::underlying_type<T>::type tmp{};
  1228. auto restOrError = parseTo(in, tmp);
  1229. out = static_cast<T>(tmp); // Harmless if parseTo fails
  1230. return restOrError;
  1231. }
  1232. FOLLY_NODISCARD
  1233. inline Expected<StringPiece, ConversionCode> parseTo(
  1234. StringPiece in,
  1235. StringPiece& out) noexcept {
  1236. out = in;
  1237. return StringPiece{in.end(), in.end()};
  1238. }
  1239. FOLLY_NODISCARD
  1240. inline Expected<StringPiece, ConversionCode> parseTo(
  1241. StringPiece in,
  1242. std::string& out) {
  1243. out.clear();
  1244. out.append(in.data(), in.size()); // TODO try/catch?
  1245. return StringPiece{in.end(), in.end()};
  1246. }
  1247. FOLLY_NODISCARD
  1248. inline Expected<StringPiece, ConversionCode> parseTo(
  1249. StringPiece in,
  1250. fbstring& out) {
  1251. out.clear();
  1252. out.append(in.data(), in.size()); // TODO try/catch?
  1253. return StringPiece{in.end(), in.end()};
  1254. }
  1255. namespace detail {
  1256. template <typename Tgt>
  1257. using ParseToResult = decltype(parseTo(StringPiece{}, std::declval<Tgt&>()));
  1258. struct CheckTrailingSpace {
  1259. Expected<Unit, ConversionCode> operator()(StringPiece sp) const {
  1260. auto e = enforceWhitespaceErr(sp);
  1261. if (UNLIKELY(e != ConversionCode::SUCCESS)) {
  1262. return makeUnexpected(e);
  1263. }
  1264. return unit;
  1265. }
  1266. };
  1267. template <class Error>
  1268. struct ReturnUnit {
  1269. template <class T>
  1270. constexpr Expected<Unit, Error> operator()(T&&) const {
  1271. return unit;
  1272. }
  1273. };
  1274. // Older versions of the parseTo customization point threw on error and
  1275. // returned void. Handle that.
  1276. template <class Tgt>
  1277. inline typename std::enable_if<
  1278. std::is_void<ParseToResult<Tgt>>::value,
  1279. Expected<StringPiece, ConversionCode>>::type
  1280. parseToWrap(StringPiece sp, Tgt& out) {
  1281. parseTo(sp, out);
  1282. return StringPiece(sp.end(), sp.end());
  1283. }
  1284. template <class Tgt>
  1285. inline typename std::enable_if<
  1286. !std::is_void<ParseToResult<Tgt>>::value,
  1287. ParseToResult<Tgt>>::type
  1288. parseToWrap(StringPiece sp, Tgt& out) {
  1289. return parseTo(sp, out);
  1290. }
  1291. template <typename Tgt>
  1292. using ParseToError = ExpectedErrorType<decltype(
  1293. detail::parseToWrap(StringPiece{}, std::declval<Tgt&>()))>;
  1294. } // namespace detail
  1295. /**
  1296. * String or StringPiece to target conversion. Accepts leading and trailing
  1297. * whitespace, but no non-space trailing characters.
  1298. */
  1299. template <class Tgt>
  1300. inline typename std::enable_if<
  1301. !std::is_same<StringPiece, Tgt>::value,
  1302. Expected<Tgt, detail::ParseToError<Tgt>>>::type
  1303. tryTo(StringPiece src) {
  1304. Tgt result{};
  1305. using Error = detail::ParseToError<Tgt>;
  1306. using Check = typename std::conditional<
  1307. std::is_arithmetic<Tgt>::value,
  1308. detail::CheckTrailingSpace,
  1309. detail::ReturnUnit<Error>>::type;
  1310. return parseTo(src, result).then(Check(), [&](Unit) {
  1311. return std::move(result);
  1312. });
  1313. }
  1314. template <class Tgt, class Src>
  1315. inline typename std::enable_if<
  1316. IsSomeString<Src>::value && !std::is_same<StringPiece, Tgt>::value,
  1317. Tgt>::type
  1318. to(Src const& src) {
  1319. return to<Tgt>(StringPiece(src.data(), src.size()));
  1320. }
  1321. template <class Tgt>
  1322. inline
  1323. typename std::enable_if<!std::is_same<StringPiece, Tgt>::value, Tgt>::type
  1324. to(StringPiece src) {
  1325. Tgt result{};
  1326. using Error = detail::ParseToError<Tgt>;
  1327. using Check = typename std::conditional<
  1328. std::is_arithmetic<Tgt>::value,
  1329. detail::CheckTrailingSpace,
  1330. detail::ReturnUnit<Error>>::type;
  1331. auto tmp = detail::parseToWrap(src, result);
  1332. return tmp
  1333. .thenOrThrow(
  1334. Check(),
  1335. [&](Error e) { throw_exception(makeConversionError(e, src)); })
  1336. .thenOrThrow(
  1337. [&](Unit) { return std::move(result); },
  1338. [&](Error e) {
  1339. throw_exception(makeConversionError(e, tmp.value()));
  1340. });
  1341. }
  1342. /**
  1343. * tryTo/to that take the strings by pointer so the caller gets information
  1344. * about how much of the string was consumed by the conversion. These do not
  1345. * check for trailing whitepsace.
  1346. */
  1347. template <class Tgt>
  1348. Expected<Tgt, detail::ParseToError<Tgt>> tryTo(StringPiece* src) {
  1349. Tgt result;
  1350. return parseTo(*src, result).then([&, src](StringPiece sp) -> Tgt {
  1351. *src = sp;
  1352. return std::move(result);
  1353. });
  1354. }
  1355. template <class Tgt>
  1356. Tgt to(StringPiece* src) {
  1357. Tgt result{};
  1358. using Error = detail::ParseToError<Tgt>;
  1359. return parseTo(*src, result)
  1360. .thenOrThrow(
  1361. [&, src](StringPiece sp) -> Tgt {
  1362. *src = sp;
  1363. return std::move(result);
  1364. },
  1365. [=](Error e) { return makeConversionError(e, *src); });
  1366. }
  1367. /*******************************************************************************
  1368. * Enum to anything and back
  1369. ******************************************************************************/
  1370. template <class Tgt, class Src>
  1371. typename std::enable_if<
  1372. std::is_enum<Src>::value && !std::is_same<Src, Tgt>::value &&
  1373. !std::is_convertible<Tgt, StringPiece>::value,
  1374. Expected<Tgt, ConversionCode>>::type
  1375. tryTo(const Src& value) {
  1376. using I = typename std::underlying_type<Src>::type;
  1377. return tryTo<Tgt>(static_cast<I>(value));
  1378. }
  1379. template <class Tgt, class Src>
  1380. typename std::enable_if<
  1381. !std::is_convertible<Src, StringPiece>::value && std::is_enum<Tgt>::value &&
  1382. !std::is_same<Src, Tgt>::value,
  1383. Expected<Tgt, ConversionCode>>::type
  1384. tryTo(const Src& value) {
  1385. using I = typename std::underlying_type<Tgt>::type;
  1386. return tryTo<I>(value).then([](I i) { return static_cast<Tgt>(i); });
  1387. }
  1388. template <class Tgt, class Src>
  1389. typename std::enable_if<
  1390. std::is_enum<Src>::value && !std::is_same<Src, Tgt>::value &&
  1391. !std::is_convertible<Tgt, StringPiece>::value,
  1392. Tgt>::type
  1393. to(const Src& value) {
  1394. return to<Tgt>(static_cast<typename std::underlying_type<Src>::type>(value));
  1395. }
  1396. template <class Tgt, class Src>
  1397. typename std::enable_if<
  1398. !std::is_convertible<Src, StringPiece>::value && std::is_enum<Tgt>::value &&
  1399. !std::is_same<Src, Tgt>::value,
  1400. Tgt>::type
  1401. to(const Src& value) {
  1402. return static_cast<Tgt>(to<typename std::underlying_type<Tgt>::type>(value));
  1403. }
  1404. } // namespace folly