abacus: bignum: add output operator

This commit is contained in:
Bruno BELANYI 2021-08-20 18:09:28 +02:00
parent 0a5fb471e4
commit ad5092ea8d
3 changed files with 43 additions and 0 deletions

View file

@ -1,6 +1,8 @@
#include "bignum.hh" #include "bignum.hh"
#include <algorithm> #include <algorithm>
#include <iostream>
#include <iterator>
#include <cassert> #include <cassert>
#include <cmath> #include <cmath>
@ -27,6 +29,20 @@ BigNum::BigNum(std::int64_t number) {
assert(is_canonicalized()); assert(is_canonicalized());
} }
std::ostream& BigNum::dump(std::ostream& out) const {
if (sign_ == 0) {
return out << '0';
}
if (sign_ < 0) {
out << '-';
}
std::copy(digits_.rbegin(), digits_.rend(),
std::ostream_iterator<int>(out));
return out;
}
void BigNum::flip_sign() { void BigNum::flip_sign() {
assert(is_canonicalized()); assert(is_canonicalized());

View file

@ -1,5 +1,6 @@
#pragma once #pragma once
#include <iosfwd>
#include <vector> #include <vector>
#include <cstdint> #include <cstdint>
@ -10,6 +11,10 @@ class BigNum {
public: public:
explicit BigNum(std::int64_t number); explicit BigNum(std::int64_t number);
friend std::ostream& operator<<(std::ostream& out, BigNum const& num) {
return num.dump(out);
}
friend BigNum operator+(BigNum const& rhs) { friend BigNum operator+(BigNum const& rhs) {
return rhs; return rhs;
} }
@ -45,6 +50,8 @@ public:
} }
private: private:
std::ostream& dump(std::ostream& out) const;
void flip_sign(); void flip_sign();
bool equal(BigNum const& rhs) const; bool equal(BigNum const& rhs) const;

View file

@ -1,9 +1,29 @@
#include <sstream>
#include <gtest/gtest.h> #include <gtest/gtest.h>
#include "bignum.hh" #include "bignum.hh"
using namespace abacus::bignum; using namespace abacus::bignum;
TEST(BigNum, dump) {
auto const zero = BigNum(0);
auto const one = BigNum(1);
auto const minus_one = BigNum(-1);
auto const forty_two = BigNum(42);
auto const to_str = [](auto num) {
std::stringstream str;
str << num;
return str.str();
};
ASSERT_EQ(to_str(zero), "0");
ASSERT_EQ(to_str(one), "1");
ASSERT_EQ(to_str(minus_one), "-1");
ASSERT_EQ(to_str(forty_two), "42");
}
TEST(BigNum, equality) { TEST(BigNum, equality) {
auto const zero = BigNum(0); auto const zero = BigNum(0);
auto const one = BigNum(1); auto const one = BigNum(1);