| 26 | namespace internal { |
| 27 | |
| 28 | class BigInteger { |
| 29 | public: |
| 30 | typedef uint64_t Type; |
| 31 | |
| 32 | BigInteger(const BigInteger& rhs) : count_(rhs.count_) { |
| 33 | std::memcpy(digits_, rhs.digits_, count_ * sizeof(Type)); |
| 34 | } |
| 35 | |
| 36 | explicit BigInteger(uint64_t u) : count_(1) { |
| 37 | digits_[0] = u; |
| 38 | } |
| 39 | |
| 40 | BigInteger(const char* decimals, size_t length) : count_(1) { |
| 41 | RAPIDJSON_ASSERT(length > 0); |
| 42 | digits_[0] = 0; |
| 43 | size_t i = 0; |
| 44 | const size_t kMaxDigitPerIteration = 19; // 2^64 = 18446744073709551616 > 10^19 |
| 45 | while (length >= kMaxDigitPerIteration) { |
| 46 | AppendDecimal64(decimals + i, decimals + i + kMaxDigitPerIteration); |
| 47 | length -= kMaxDigitPerIteration; |
| 48 | i += kMaxDigitPerIteration; |
| 49 | } |
| 50 | |
| 51 | if (length > 0) |
| 52 | AppendDecimal64(decimals + i, decimals + i + length); |
| 53 | } |
| 54 | |
| 55 | BigInteger& operator=(const BigInteger &rhs) |
| 56 | { |
| 57 | if (this != &rhs) { |
| 58 | count_ = rhs.count_; |
| 59 | std::memcpy(digits_, rhs.digits_, count_ * sizeof(Type)); |
| 60 | } |
| 61 | return *this; |
| 62 | } |
| 63 | |
| 64 | BigInteger& operator=(uint64_t u) { |
| 65 | digits_[0] = u; |
| 66 | count_ = 1; |
| 67 | return *this; |
| 68 | } |
| 69 | |
| 70 | BigInteger& operator+=(uint64_t u) { |
| 71 | Type backup = digits_[0]; |
| 72 | digits_[0] += u; |
| 73 | for (size_t i = 0; i < count_ - 1; i++) { |
| 74 | if (digits_[i] >= backup) |
| 75 | return *this; // no carry |
| 76 | backup = digits_[i + 1]; |
| 77 | digits_[i + 1] += 1; |
| 78 | } |
| 79 | |
| 80 | // Last carry |
| 81 | if (digits_[count_ - 1] < backup) |
| 82 | PushBack(1); |
| 83 | |
| 84 | return *this; |
| 85 | } |