Skip to content

StringSegment IndexOf behavior #53727

Description

@hrrrrustic

Description

Working on reopening PR for #45021 (first one was closed due to inactivity)
Found a few more strange behaviors

First:
There is no check for the right bound in IndexOf like in the IndexOfAny
IndexOfAny:

if (startIndex < 0 || Offset + startIndex > Buffer.Length)
{
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.start);
}
if (count < 0 || Offset + startIndex + count > Buffer.Length)
{
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.count);
}
index = Buffer.IndexOfAny(anyOf, Offset + startIndex, count);

IndexOf:

if (!HasValue || start < 0 || (uint)offset > (uint)Buffer.Length)
{
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.start);
}
if (count < 0)
{
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.count);
}
int index = AsSpan().Slice(start, count).IndexOf(c);

Anyway, exception will be thrown in Span<T>.Slice method (exception message will be a little different), but I don't think this is by design 😄

Second:
Check for the right bound above (IndexOfAny) is quite weird, it allows to get index from original string
Example:

public static void Main(string[] args)
        {
            StringSegment segment = new StringSegment("12345", 0, 1);
            var index = segment.IndexOfAny(new[] { '5' }, 2, 3);
            Console.WriteLine(index); // Prints 4 
        }

I believe that correct value here should be -1, am I missing something?
UPD: OutOfRangeException should be thrown
So it seems like Buffer.Length have to be replaced with Length property

Regression?

Fixes will be breaking changes, but for the original issue (#45021) it was ok #46432 (comment)

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions