1 // Copyright 2014 The PDFium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 // Original code by Matt McCutchen, see the LICENSE file.
6
7 #include <ostream>
8
9 #include "BigIntegerUtils.hh"
10 #include "BigUnsignedInABase.hh"
11
bigUnsignedToString(const BigUnsigned & x)12 std::string bigUnsignedToString(const BigUnsigned &x) {
13 return std::string(BigUnsignedInABase(x, 10));
14 }
15
bigIntegerToString(const BigInteger & x)16 std::string bigIntegerToString(const BigInteger &x) {
17 return (x.getSign() == BigInteger::negative)
18 ? (std::string("-") + bigUnsignedToString(x.getMagnitude()))
19 : (bigUnsignedToString(x.getMagnitude()));
20 }
21
stringToBigUnsigned(const std::string & s)22 BigUnsigned stringToBigUnsigned(const std::string &s) {
23 return BigUnsigned(BigUnsignedInABase(s, 10));
24 }
25
stringToBigInteger(const std::string & s)26 BigInteger stringToBigInteger(const std::string &s) {
27 // Recognize a sign followed by a BigUnsigned.
28 return (s[0] == '-') ? BigInteger(stringToBigUnsigned(s.substr(1, s.length() - 1)), BigInteger::negative)
29 : (s[0] == '+') ? BigInteger(stringToBigUnsigned(s.substr(1, s.length() - 1)))
30 : BigInteger(stringToBigUnsigned(s));
31 }
32
operator <<(std::ostream & os,const BigUnsigned & x)33 std::ostream &operator <<(std::ostream &os, const BigUnsigned &x) {
34 BigUnsignedInABase::Base base;
35 long osFlags = os.flags();
36 if (osFlags & os.dec)
37 base = 10;
38 else if (osFlags & os.hex) {
39 base = 16;
40 if (osFlags & os.showbase)
41 os << "0x";
42 } else if (osFlags & os.oct) {
43 base = 8;
44 if (osFlags & os.showbase)
45 os << '0';
46 } else
47 abort();
48
49 std::string s = std::string(BigUnsignedInABase(x, base));
50 os << s;
51 return os;
52 }
53
operator <<(std::ostream & os,const BigInteger & x)54 std::ostream &operator <<(std::ostream &os, const BigInteger &x) {
55 if (x.getSign() == BigInteger::negative)
56 os << '-';
57 os << x.getMagnitude();
58 return os;
59 }
60