Skip to content
Snippets Groups Projects
Unverified Commit 577f0332 authored by Shaopeng Wang's avatar Shaopeng Wang Committed by GitHub
Browse files

Impl saturating_abs for Fixed128. (#116)

parent 9ff9c263
No related branches found
No related tags found
No related merge requests found
...@@ -172,6 +172,19 @@ impl Fixed128 { ...@@ -172,6 +172,19 @@ impl Fixed128 {
pub fn is_zero(&self) -> bool { pub fn is_zero(&self) -> bool {
self.0 == 0 self.0 == 0
} }
/// Saturating absolute value. Returning MAX if `parts` == i128::MIN instead of overflowing.
pub fn saturating_abs(&self) -> Self {
if self.0 == i128::min_value() {
return Fixed128::max_value();
}
if self.0.is_negative() {
Fixed128::from_parts(self.0 * -1)
} else {
*self
}
}
} }
impl Saturating for Fixed128 { impl Saturating for Fixed128 {
...@@ -530,4 +543,14 @@ mod tests { ...@@ -530,4 +543,14 @@ mod tests {
let deserialized: Fixed128 = serde_json::from_str(&serialized).unwrap(); let deserialized: Fixed128 = serde_json::from_str(&serialized).unwrap();
assert_eq!(deserialized, minus_two_point_five); assert_eq!(deserialized, minus_two_point_five);
} }
#[test]
fn saturating_abs_should_work() {
// normal
assert_eq!(Fixed128::from_parts(1).saturating_abs(), Fixed128::from_parts(1));
assert_eq!(Fixed128::from_parts(-1).saturating_abs(), Fixed128::from_parts(1));
// saturating
assert_eq!(Fixed128::min_value().saturating_abs(), Fixed128::max_value());
}
} }
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment