Finish the MathNumber implementations.

master
Tom Alexander 4 years ago
parent f783f45d24
commit fdd467298a
Signed by: talexander
GPG Key ID: D3A179C9A53C0EDE

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

Loading…
Cancel
Save