Skip to content

Commit

Permalink
Merge pull request #315 from HubSpot/use-long-int
Browse files Browse the repository at this point in the history
Return long value from int filter if over max int length.
  • Loading branch information
mattcoley authored Mar 25, 2019
2 parents 1d475ba + 254192e commit a4846c5
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 7 deletions.
21 changes: 14 additions & 7 deletions src/main/java/com/hubspot/jinjava/lib/filter/IntFilter.java
Original file line number Diff line number Diff line change
Expand Up @@ -37,33 +37,40 @@ public String getName() {
public Object filter(Object var, JinjavaInterpreter interpreter,
String... args) {

int defaultVal = 0;
Long defaultVal = 0L;
if (args.length > 0) {
defaultVal = NumberUtils.toInt(args[0], 0);
defaultVal = NumberUtils.toLong(args[0], 0);
}

if (var == null) {
return defaultVal;
return convertResult(defaultVal);
}

if (Number.class.isAssignableFrom(var.getClass())) {
return ((Number) var).intValue();
return convertResult(((Number) var).longValue());
}

String input = var.toString().trim();
Locale locale = interpreter.getConfig().getLocale();
NumberFormat numberFormat = NumberFormat.getNumberInstance(locale);
ParsePosition pp = new ParsePosition(0);
int result;
Long result;
try {
result = numberFormat.parse(input, pp).intValue();
result = numberFormat.parse(input, pp).longValue();
} catch (Exception e) {
result = defaultVal;
}
if (pp.getErrorIndex() != -1 || pp.getIndex() != input.length()) {
result = defaultVal;
}
return result;
return convertResult(result);
}

private Object convertResult(Long result) {
if (result > Integer.MAX_VALUE) {
return result;
}
return result.intValue();
}

}
10 changes: 10 additions & 0 deletions src/test/java/com/hubspot/jinjava/lib/filter/IntFilterTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,16 @@ public void itInterpretsFrenchCommasAndPeriodsWithFrenchLocale() {
assertThat(filter.filter("123\u00A0123,12", interpreter)).isEqualTo(123123);
}

@Test
public void itUsesLongsForLargeValues() {
assertThat(filter.filter("1000000000001", interpreter)).isEqualTo(1000000000001L);
}

@Test
public void itUsesLongsForLargeValueDefaults() {
assertThat(filter.filter("not a number", interpreter, "1000000000001")).isEqualTo(1000000000001L);
}

@Test
public void itConvertsProperlyInExpressionTest() {
assertThat(interpreter.render("{{ '3'|int in [null, 4, 5, 6, null, 3] }}")).isEqualTo("true");
Expand Down

0 comments on commit a4846c5

Please sign in to comment.