Finish the MathNumber implementations.

This commit is contained in:
Tom Alexander 2020-06-13 22:46:03 -04:00
parent f783f45d24
commit fdd467298a
Signed by: talexander
GPG Key ID: D3A179C9A53C0EDE

View File

@ -1,4 +1,5 @@
use crate::parser::OwnedLiteral;
use std::convert::TryFrom;
use std::convert::TryInto;
use std::ops::Add;
use std::ops::Div;
@ -138,13 +139,25 @@ impl Rem<MathNumber> for MathNumber {
impl MathNumber {
fn math_abs(&self) -> Option<OwnedLiteral> {
todo!()
match self {
MathNumber::Failure => None,
MathNumber::Integer(num) => num.abs().try_into().ok(),
MathNumber::Decimal(num) => Some(OwnedLiteral::LFloat(num.abs())),
}
}
fn math_floor(&self) -> Option<OwnedLiteral> {
todo!()
match self {
MathNumber::Failure => None,
MathNumber::Integer(num) => (*num).try_into().ok(),
MathNumber::Decimal(num) => Some(OwnedLiteral::LFloat(num.floor())),
}
}
fn math_ceil(&self) -> Option<OwnedLiteral> {
todo!()
match self {
MathNumber::Failure => None,
MathNumber::Integer(num) => (*num).try_into().ok(),
MathNumber::Decimal(num) => Some(OwnedLiteral::LFloat(num.ceil())),
}
}
}
@ -156,25 +169,19 @@ where
R: Into<i128>,
F: Fn(i128, i128) -> i128,
{
let result = operation(left.into(), right.into());
std::convert::TryInto::<u64>::try_into(result)
.map(OwnedLiteral::LPositiveInteger)
.ok()
.or(std::convert::TryInto::<i64>::try_into(result)
.map(OwnedLiteral::LNegativeInteger)
.ok())
operation(left.into(), right.into()).try_into().ok()
}
// /// For math operations that take in integers and return integers
// /// (add, subtract, multiply)
// fn math_floats<L, R, F>(left: L, right: R, operation: F) -> Option<OwnedLiteral>
// where
// L: Into<f64>,
// R: Into<f64>,
// F: Fn(f64, f64) -> f64,
// {
// let result = operation(left.into(), right.into());
// std::convert::TryInto::<f64>::try_into(result)
// .map(OwnedLiteral::LFloat)
// .ok()
// }
impl TryFrom<i128> for OwnedLiteral {
type Error = &'static str;
fn try_from(original: i128) -> Result<Self, Self::Error> {
std::convert::TryInto::<u64>::try_into(original)
.map(OwnedLiteral::LPositiveInteger)
.ok()
.or(std::convert::TryInto::<i64>::try_into(original)
.map(OwnedLiteral::LNegativeInteger)
.ok())
.ok_or("Value does not fit into either u64 or i64")
}
}