Implement number casting.

This commit is contained in:
Tom Alexander 2020-06-13 19:55:40 -04:00
parent 9eb70f436c
commit dcbf8e83f6
Signed by: talexander
GPG Key ID: D3A179C9A53C0EDE
2 changed files with 34 additions and 2 deletions

View File

@ -315,7 +315,22 @@ impl Loopable for serde_json::Value {
impl Castable for serde_json::Value {
fn cast_to_type<'a>(&'a self, target: &str) -> Option<IceResult<'a>> {
todo!()
match (self, target) {
(serde_json::Value::String(text), "number") => text
.parse::<u64>()
.map(|num| IceResult::from_owned(OwnedLiteral::LPositiveInteger(num)))
.or_else(|_| {
text.parse::<i64>()
.map(|num| IceResult::from_owned(OwnedLiteral::LNegativeInteger(num)))
})
.or_else(|_| {
text.parse::<f64>()
.map(|num| IceResult::from_owned(OwnedLiteral::LFloat(num)))
})
.ok(),
(serde_json::Value::Number(_), "number") => Some(IceResult::from_borrowed(self)),
(_, _) => panic!("Unimplemented cast"),
}
}
}

View File

@ -170,7 +170,24 @@ impl Walkable for OwnedLiteral {
impl Castable for OwnedLiteral {
fn cast_to_type<'a>(&'a self, target: &str) -> Option<IceResult<'a>> {
todo!()
match (self, target) {
(OwnedLiteral::LString(text), "number") => text
.parse::<u64>()
.map(|num| IceResult::from_owned(OwnedLiteral::LPositiveInteger(num)))
.or_else(|_| {
text.parse::<i64>()
.map(|num| IceResult::from_owned(OwnedLiteral::LNegativeInteger(num)))
})
.or_else(|_| {
text.parse::<f64>()
.map(|num| IceResult::from_owned(OwnedLiteral::LFloat(num)))
})
.ok(),
(OwnedLiteral::LPositiveInteger(_), "number") => Some(IceResult::from_borrowed(self)),
(OwnedLiteral::LNegativeInteger(_), "number") => Some(IceResult::from_borrowed(self)),
(OwnedLiteral::LFloat(_), "number") => Some(IceResult::from_borrowed(self)),
(_, _) => panic!("Unimplemented cast"),
}
}
}