J2N icon indicating copy to clipboard operation
J2N copied to clipboard

Bug: Inconsistent behavior of Indexof() and LastIndexOf()

Open NightOwl888 opened this issue 6 months ago • 0 comments

We need our own implementations of IndexOf() and LastIndexOf() on StringBuilder because they are not provided in .NET.

The J2N implementations we have account for Ordinal and OrdinalIgnoreCase of StringComparison, but all other options call ToString() on the StringBuilder and then cascade the call to string.IndexOf() and string.LastIndexOf().

However, in the JDK and Apache Harmony, the overload that allows you to specify startIndex/fromIndex do not have any exceptions thrown on the bounds and instead correct anything over Length - 1 to be equivalent to Length - 1 and anything below zero will return -1. So, this behavior is inconsistent between Java and .NET.

However, we have no way to re-implement IndexOf() and LastIndexOf() on String or ReadOnlySpan<char> so the most logical thing to do is to change the Ordinal and OrdinalIgnoreCase to throw when Length is passed so it is consistent with the rest of the .NET behavior. The only downside is that this means that any logic written in Java that is sloppy with the bounds will need to be corrected. However, we could simply provide a note in the API docs that the behavior is inconsistent with Java and consistent with .NET.

Whatever the fix, it will require a breaking behavior change and cannot be addressed without a major version bump.

NightOwl888 avatar Dec 24 '23 15:12 NightOwl888