abacus: bignum: add input operator

This commit is contained in:
Bruno BELANYI 2021-08-20 19:00:53 +02:00
parent fe01661613
commit d40c109fb7
3 changed files with 54 additions and 0 deletions

View file

@ -105,6 +105,41 @@ std::ostream& BigNum::dump(std::ostream& out) const {
return out; return out;
} }
std::istream& BigNum::read(std::istream& in) {
bool parsed = false;
bool leading = true;
if (in.peek() == '-') {
in.get();
sign_ = -1;
} else {
sign_ = 1;
}
digits_type digits;
while (std::isdigit(in.peek())) {
parsed = true;
int digit = in.get() - '0';
if (digit != 0 || !leading) {
digits.push_back(digit);
leading = false;
}
}
if (leading) {
sign_ = 0;
}
if (!parsed) {
in.setstate(std::ios::failbit);
} else {
std::reverse(digits.begin(), digits.end());
digits_ = std::move(digits);
}
return in;
}
void BigNum::flip_sign() { void BigNum::flip_sign() {
assert(is_canonicalized()); assert(is_canonicalized());

View file

@ -15,6 +15,10 @@ public:
return num.dump(out); return num.dump(out);
} }
friend std::istream& operator>>(std::istream& in, BigNum& num) {
return num.read(in);
}
friend BigNum operator+(BigNum const& rhs) { friend BigNum operator+(BigNum const& rhs) {
return rhs; return rhs;
} }
@ -73,6 +77,7 @@ public:
private: private:
std::ostream& dump(std::ostream& out) const; std::ostream& dump(std::ostream& out) const;
std::istream& read(std::istream& in);
void flip_sign(); void flip_sign();
void add(BigNum const& rhs); void add(BigNum const& rhs);

View file

@ -24,6 +24,20 @@ TEST(BigNum, dump) {
EXPECT_EQ(to_str(forty_two), "42"); EXPECT_EQ(to_str(forty_two), "42");
} }
TEST(BigNum, read) {
auto const from_str = [](auto num) -> BigNum {
std::stringstream str(num);
BigNum res;
EXPECT_TRUE(str >> res);
return res;
};
EXPECT_EQ(from_str("0"), BigNum(0));
EXPECT_EQ(from_str("1"), BigNum(1));
EXPECT_EQ(from_str("-1"), BigNum(-1));
EXPECT_EQ(from_str("42"), BigNum(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);