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

Make number coercion behave more like Ruby #473

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion crates/core/src/model/find.rs
Original file line number Diff line number Diff line change
Expand Up @@ -160,7 +160,7 @@ fn try_find_owned<'o, 'i>(

fn augmented_get<'o>(value: &'o dyn ValueView, index: &ScalarCow<'_>) -> Option<ValueCow<'o>> {
if let Some(arr) = value.as_array() {
if let Some(index) = index.to_integer() {
if let Some(index) = index.to_integer_strict() {
arr.get(index).map(ValueCow::Borrowed)
} else {
match &*index.to_kstr() {
Expand Down
38 changes: 31 additions & 7 deletions crates/core/src/model/scalar/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -95,17 +95,41 @@ impl<'s> ScalarCow<'s> {
}
}

/// Interpret as an integer, if possible
/// Interpret as an integer, if possible. Returns 0 if given a non-parseable string, and truncates floats.
pub fn to_integer(&self) -> Option<i64> {
match self.0 {
ScalarCowEnum::Integer(ref x) => Some(*x),
ScalarCowEnum::Float(ref x) => Some(x.trunc() as i64),
ScalarCowEnum::Str(ref x) => Some(
x.parse::<f64>()
.map(|parsed| parsed.trunc() as i64)
.unwrap_or(0),
),
_ => None,
}
}

/// Interpret as an integer, if possible. Return None if given a float or non-parseable string.
pub fn to_integer_strict(&self) -> Option<i64> {
match self.0 {
ScalarCowEnum::Integer(ref x) => Some(*x),
ScalarCowEnum::Str(ref x) => x.parse::<i64>().ok(),
_ => None,
}
}

/// Interpret as a float, if possible
/// Interpret as a float, if possible. Return 0.0 if given a non-parseable string.
pub fn to_float(&self) -> Option<f64> {
match self.0 {
ScalarCowEnum::Integer(ref x) => Some(*x as f64),
ScalarCowEnum::Float(ref x) => Some(*x),
ScalarCowEnum::Str(ref x) => Some(x.parse::<f64>().unwrap_or(0.0)),
_ => None,
}
}

/// Interpret as a float, if possible. Return None if given a non-parseable string.
pub fn to_float_strict(&self) -> Option<f64> {
match self.0 {
ScalarCowEnum::Integer(ref x) => Some(*x as f64),
ScalarCowEnum::Float(ref x) => Some(*x),
Expand Down Expand Up @@ -915,19 +939,19 @@ mod test {
#[test]
fn test_to_integer_float() {
let val: ScalarCow<'_> = 42f64.into();
assert_eq!(val.to_integer(), None);
assert_eq!(val.to_integer(), Some(42));

let val: ScalarCow<'_> = 42.34.into();
assert_eq!(val.to_integer(), None);
assert_eq!(val.to_integer(), Some(42));
}

#[test]
fn test_to_integer_str() {
let val: ScalarCow<'_> = "foobar".into();
assert_eq!(val.to_integer(), None);
assert_eq!(val.to_integer(), Some(0));

let val: ScalarCow<'_> = "42.34".into();
assert_eq!(val.to_integer(), None);
assert_eq!(val.to_integer(), Some(42));

let val: ScalarCow<'_> = "42".into();
assert_eq!(val.to_integer(), Some(42));
Expand Down Expand Up @@ -956,7 +980,7 @@ mod test {
#[test]
fn test_to_float_str() {
let val: ScalarCow<'_> = "foobar".into();
assert_eq!(val.to_float(), None);
assert_eq!(val.to_float(), Some(0.0));

let val: ScalarCow<'_> = "42.34".into();
assert_eq!(val.to_float(), Some(42.34));
Expand Down
4 changes: 2 additions & 2 deletions crates/derive/src/filter_parameters.rs
Original file line number Diff line number Diff line change
Expand Up @@ -499,7 +499,7 @@ fn generate_evaluate_field(field: &FilterParameter<'_>) -> TokenStream {
},
FilterParameterType::Integer => quote! {
#name.as_scalar()
.and_then(|s| s.to_integer())
.and_then(|s| s.to_integer_strict())
.ok_or_else(||
::liquid_core::error::Error::with_msg("Invalid argument")
.context("argument", #liquid_name)
Expand All @@ -508,7 +508,7 @@ fn generate_evaluate_field(field: &FilterParameter<'_>) -> TokenStream {
},
FilterParameterType::Float => quote! {
#name.as_scalar()
.and_then(|s| s.to_float())
.and_then(|s| s.to_float_strict())
.ok_or_else(||
::liquid_core::error::Error::with_msg("Invalid argument")
.context("argument", #liquid_name)
Expand Down
4 changes: 2 additions & 2 deletions crates/lib/src/stdlib/blocks/for_block.rs
Original file line number Diff line number Diff line change
Expand Up @@ -510,7 +510,7 @@ fn evaluate_attr(attr: &Option<Expression>, runtime: &dyn Runtime) -> Result<Opt
let value = attr.evaluate(runtime)?;
let value = value
.as_scalar()
.and_then(|s| s.to_integer())
.and_then(|s| s.to_integer_strict())
.ok_or_else(|| unexpected_value_error("whole number", Some(value.type_name())))?
as usize;
Ok(Some(value))
Expand Down Expand Up @@ -599,7 +599,7 @@ fn int_argument(arg: &Expression, runtime: &dyn Runtime, arg_name: &str) -> Resu

let value = value
.as_scalar()
.and_then(|v| v.to_integer())
.and_then(|v| v.to_integer_strict())
.ok_or_else(|| unexpected_value_error("whole number", Some(value.type_name())))
.context_key_with(|| arg_name.to_owned().into())
.value_with(|| value.to_kstr().into_owned())?;
Expand Down
34 changes: 17 additions & 17 deletions crates/lib/src/stdlib/filters/math.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ impl Filter for AbsFilter {
.as_scalar()
.ok_or_else(|| invalid_input("Number expected"))?;
input
.to_integer()
.to_integer_strict()
.map(|i| Value::scalar(i.abs()))
.or_else(|| input.to_float().map(|i| Value::scalar(i.abs())))
.ok_or_else(|| invalid_input("Number expected"))
Expand Down Expand Up @@ -71,8 +71,8 @@ impl Filter for AtLeastFilter {
.ok_or_else(|| invalid_argument("operand", "Number expected"))?;

let result = input
.to_integer()
.and_then(|i| min.to_integer().map(|min| Value::scalar(i.max(min))))
.to_integer_strict()
.and_then(|i| min.to_integer_strict().map(|min| Value::scalar(i.max(min))))
.or_else(|| {
input
.to_float()
Expand Down Expand Up @@ -120,8 +120,8 @@ impl Filter for AtMostFilter {
.ok_or_else(|| invalid_argument("operand", "Number expected"))?;

let result = input
.to_integer()
.and_then(|i| max.to_integer().map(|max| Value::scalar(i.min(max))))
.to_integer_strict()
.and_then(|i| max.to_integer_strict().map(|max| Value::scalar(i.min(max))))
.or_else(|| {
input
.to_float()
Expand Down Expand Up @@ -169,8 +169,8 @@ impl Filter for PlusFilter {
.ok_or_else(|| invalid_argument("operand", "Number expected"))?;

let result = input
.to_integer()
.and_then(|i| operand.to_integer().map(|o| Value::scalar(i + o)))
.to_integer_strict()
.and_then(|i| operand.to_integer_strict().map(|o| Value::scalar(i + o)))
.or_else(|| {
input
.to_float()
Expand Down Expand Up @@ -218,8 +218,8 @@ impl Filter for MinusFilter {
.ok_or_else(|| invalid_argument("operand", "Number expected"))?;

let result = input
.to_integer()
.and_then(|i| operand.to_integer().map(|o| Value::scalar(i - o)))
.to_integer_strict()
.and_then(|i| operand.to_integer_strict().map(|o| Value::scalar(i - o)))
.or_else(|| {
input
.to_float()
Expand Down Expand Up @@ -267,8 +267,8 @@ impl Filter for TimesFilter {
.ok_or_else(|| invalid_argument("operand", "Number expected"))?;

let result = input
.to_integer()
.and_then(|i| operand.to_integer().map(|o| Value::scalar(i * o)))
.to_integer_strict()
.and_then(|i| operand.to_integer_strict().map(|o| Value::scalar(i * o)))
.or_else(|| {
input
.to_float()
Expand Down Expand Up @@ -315,7 +315,7 @@ impl Filter for DividedByFilter {
.as_scalar()
.ok_or_else(|| invalid_argument("operand", "Number expected"))?;

if let Some(o) = operand.to_integer() {
if let Some(o) = operand.to_integer_strict() {
if o == 0 {
return Err(invalid_argument("operand", "Can't divide by zero"));
}
Expand All @@ -326,8 +326,8 @@ impl Filter for DividedByFilter {
}

let result = input
.to_integer()
.and_then(|i| operand.to_integer().map(|o| Value::scalar(i / o)))
.to_integer_strict()
.and_then(|i| operand.to_integer_strict().map(|o| Value::scalar(i / o)))
.or_else(|| {
input
.to_float()
Expand Down Expand Up @@ -374,7 +374,7 @@ impl Filter for ModuloFilter {
.as_scalar()
.ok_or_else(|| invalid_argument("operand", "Number expected"))?;

if let Some(o) = operand.to_integer() {
if let Some(o) = operand.to_integer_strict() {
if o == 0 {
return Err(invalid_argument("operand", "Can't divide by zero"));
}
Expand All @@ -385,8 +385,8 @@ impl Filter for ModuloFilter {
}

let result = input
.to_integer()
.and_then(|i| operand.to_integer().map(|o| Value::scalar(i % o)))
.to_integer_strict()
.and_then(|i| operand.to_integer_strict().map(|o| Value::scalar(i % o)))
.or_else(|| {
input
.to_float()
Expand Down