Skip to content

Commit 4803f75

Browse files
CEL Dev Teamcopybara-github
CEL Dev Team
authored andcommitted
Fixing lastIndexOf incosistent behaviour
PiperOrigin-RevId: 751599256
1 parent 5499b4b commit 4803f75

File tree

2 files changed

+10
-6
lines changed

2 files changed

+10
-6
lines changed

extensions/src/main/java/dev/cel/extensions/CelStringExtensions.java

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -360,6 +360,10 @@ private static Long lastIndexOf(String str, String substr) throws CelEvaluationE
360360
return (long) strCpa.length();
361361
}
362362

363+
if (strCpa.length() < substrCpa.length()) {
364+
return -1L;
365+
}
366+
363367
return lastIndexOf(strCpa, substrCpa, (long) strCpa.length() - 1);
364368
}
365369

extensions/src/test/java/dev/cel/extensions/CelStringExtensionsTest.java

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -887,6 +887,7 @@ public void join_separatorIsNonString_throwsException() {
887887
}
888888

889889
@Test
890+
@TestParameters("{string: '@', lastIndexOf: '@@', expectedResult: -1}")
890891
@TestParameters("{string: '', lastIndexOf: '', expectedResult: 0}")
891892
@TestParameters("{string: 'hello mellow', lastIndexOf: '', expectedResult: 12}")
892893
@TestParameters("{string: 'hello mellow', lastIndexOf: 'hello', expectedResult: 0}")
@@ -953,21 +954,20 @@ public void lastIndexOf_unicode_success(String string, String lastIndexOf, int e
953954
}
954955

955956
@Test
957+
@TestParameters("{lastIndexOf: '@@'}")
956958
@TestParameters("{lastIndexOf: ' '}")
957959
@TestParameters("{lastIndexOf: 'a'}")
958960
@TestParameters("{lastIndexOf: 'abc'}")
959961
@TestParameters("{lastIndexOf: '나'}")
960962
@TestParameters("{lastIndexOf: '😁'}")
961-
public void lastIndexOf_onEmptyString_throwsException(String lastIndexOf) throws Exception {
963+
public void lastIndexOf_strLengthLessThanSubstrLength_returnsMinusOne(String lastIndexOf)
964+
throws Exception {
962965
CelAbstractSyntaxTree ast = COMPILER.compile("''.lastIndexOf(indexOfParam)").getAst();
963966
CelRuntime.Program program = RUNTIME.createProgram(ast);
964967

965-
CelEvaluationException exception =
966-
assertThrows(
967-
CelEvaluationException.class,
968-
() -> program.eval(ImmutableMap.of("indexOfParam", lastIndexOf)));
968+
Object evaluatedResult = program.eval(ImmutableMap.of("s", "", "indexOfParam", lastIndexOf));
969969

970-
assertThat(exception).hasMessageThat().contains("lastIndexOf failure: Offset out of range");
970+
assertThat(evaluatedResult).isEqualTo(-1);
971971
}
972972

973973
@Test

0 commit comments

Comments
 (0)