Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

copr/decimal: support neg op #2210

Merged
merged 1 commit into from Aug 24, 2017
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
44 changes: 43 additions & 1 deletion src/coprocessor/codec/mysql/decimal.rs
Expand Up @@ -14,7 +14,7 @@
use std::fmt::{self, Display, Formatter};
use std::str::{self, FromStr};
use std::io::Write;
use std::ops::{Add, Deref, DerefMut, Div, Mul, Rem, Sub};
use std::ops::{Add, Deref, DerefMut, Div, Mul, Neg, Rem, Sub};
use std::{cmp, mem, i32, i64, u32, u64};
use std::cmp::Ordering;

Expand Down Expand Up @@ -2024,6 +2024,17 @@ impl Rem for Decimal {
}
}

impl Neg for Decimal {
type Output = Decimal;

fn neg(mut self) -> Decimal {
if !self.is_zero() {
self.negative = !self.negative;
}
self
}
}

#[cfg(test)]
mod test {
use super::*;
Expand Down Expand Up @@ -2905,6 +2916,37 @@ mod test {
}
}

#[test]
fn test_neg() {
let cases = vec![
("123.45", "-123.45"),
("1", "-1"),
("1234500009876.5", "-1234500009876.5"),
("1111.5551", "-1111.5551"),
("0.555", "-0.555"),
("0", "0"),
("0.0", "0.0"),
("0.00", "0.00"),
];

for (pos, neg) in cases {
let pos_dec: Decimal = pos.parse().unwrap();
let res = -pos_dec.clone();
assert_eq!(format!("{}", res), neg);
assert!((&pos_dec + &res).is_zero());

let neg_dec: Decimal = neg.parse().unwrap();
let res = -neg_dec.clone();
assert_eq!(format!("{}", res), pos);
assert!((&neg_dec + &res).is_zero());
}

let max_dec = super::max_or_min_dec(false, 40, 20);
let min_dec = super::max_or_min_dec(true, 40, 20);
assert_eq!(min_dec, -max_dec.clone());
assert_eq!(max_dec, -min_dec.clone());
}

#[test]
fn test_max_or_min_decimal() {
let cases = vec![
Expand Down