Optional Two-phase heap tracing
[hiphop-php.git] / hphp / util / conv-10.cpp
blob4eb1f7a1f77ae2b8ce5c81de45cfc9ebdcf4e9b2
1 /*
2 +----------------------------------------------------------------------+
3 | HipHop for PHP |
4 +----------------------------------------------------------------------+
5 | Copyright (c) 2010-present Facebook, Inc. (http://www.facebook.com) |
6 +----------------------------------------------------------------------+
7 | This source file is subject to version 3.01 of the PHP license, |
8 | that is bundled with this package in the file LICENSE, and is |
9 | available through the world-wide-web at the following url: |
10 | http://www.php.net/license/3_01.txt |
11 | If you did not receive a copy of the PHP license and are unable to |
12 | obtain it through the world-wide-web, please send a note to |
13 | license@php.net so we can mail you a copy immediately. |
14 +----------------------------------------------------------------------+
17 #include "hphp/util/conv-10.h"
19 namespace HPHP {
21 folly::StringPiece conv_10(int64_t num, char* buf_end) {
22 auto p = buf_end;
23 uint64_t magnitude;
26 * On a 2's complement machine, negating the most negative integer
27 * results in a number that cannot be represented as a signed integer.
28 * Here is what we do to obtain the number's magnitude:
29 * a. add 1 to the number
30 * b. negate it (becomes positive)
31 * c. convert it to unsigned
32 * d. add 1
34 if (num < 0) {
35 magnitude = static_cast<uint64_t>(-(num + 1)) + 1;
36 } else {
37 magnitude = static_cast<uint64_t>(num);
41 * We use a do-while loop so that we write at least 1 digit
43 do {
44 auto const q = magnitude / 10;
45 auto const r = static_cast<uint32_t>(magnitude % 10);
46 *--p = r + '0';
47 magnitude = q;
48 } while (magnitude);
50 if (num < 0) *--p = '-';
51 return folly::StringPiece{p, static_cast<size_t>(buf_end - p)};