/src/botan/src/lib/math/bigint/big_io.cpp
Line | Count | Source (jump to first uncovered line) |
1 | | /* |
2 | | * BigInt Input/Output |
3 | | * (C) 1999-2007 Jack Lloyd |
4 | | * |
5 | | * Botan is released under the Simplified BSD License (see license.txt) |
6 | | */ |
7 | | |
8 | | #include <botan/bigint.h> |
9 | | #include <istream> |
10 | | #include <ostream> |
11 | | |
12 | | namespace Botan { |
13 | | |
14 | | /* |
15 | | * Write the BigInt into a stream |
16 | | */ |
17 | | std::ostream& operator<<(std::ostream& stream, const BigInt& n) |
18 | 0 | { |
19 | 0 | const auto stream_flags = stream.flags(); |
20 | 0 | if(stream_flags & std::ios::oct) |
21 | 0 | throw Invalid_Argument("Octal output of BigInt not supported"); |
22 | | |
23 | 0 | const size_t base = (stream_flags & std::ios::hex) ? 16 : 10; |
24 | |
|
25 | 0 | if(n.is_zero()) |
26 | 0 | stream.write("0", 1); |
27 | 0 | else |
28 | 0 | { |
29 | 0 | if(n.is_negative()) |
30 | 0 | stream.write("-", 1); |
31 | |
|
32 | 0 | std::string enc; |
33 | |
|
34 | 0 | if(base == 10) |
35 | 0 | enc = n.to_dec_string(); |
36 | 0 | else |
37 | 0 | enc = n.to_hex_string(); |
38 | |
|
39 | 0 | stream.write(enc.data(), enc.size()); |
40 | 0 | } |
41 | 0 | if(!stream.good()) |
42 | 0 | throw Stream_IO_Error("BigInt output operator has failed"); |
43 | 0 | return stream; |
44 | 0 | } |
45 | | |
46 | | /* |
47 | | * Read the BigInt from a stream |
48 | | */ |
49 | | std::istream& operator>>(std::istream& stream, BigInt& n) |
50 | 0 | { |
51 | 0 | std::string str; |
52 | 0 | std::getline(stream, str); |
53 | 0 | if(stream.bad() || (stream.fail() && !stream.eof())) |
54 | 0 | throw Stream_IO_Error("BigInt input operator has failed"); |
55 | 0 | n = BigInt(str); |
56 | 0 | return stream; |
57 | 0 | } |
58 | | |
59 | | } |