Skip to content
This repository has been archived by the owner on Jan 23, 2023. It is now read-only.

Implements BlobReader.IndexOf(byte) #12308

Merged
merged 1 commit into from Oct 3, 2016
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
Expand Up @@ -515,7 +515,11 @@ internal byte[] PeekBytes(int offset, int byteCount)
internal int IndexOf(byte b, int start)
{
CheckBounds(start, 0);
return IndexOfUnchecked(b, start);
}

internal int IndexOfUnchecked(byte b, int start)
{
byte* p = Pointer + start;
byte* end = Pointer + Length;
while (p < end)
Expand Down
Expand Up @@ -335,6 +335,22 @@ public SignatureHeader ReadSignatureHeader()
return new SignatureHeader(ReadByte());
}

/// <summary>
/// Finds specified byte in the blob following the current position.
/// </summary>
/// <returns>
/// Index relative to the current position, or -1 if the byte is not found in the blob following the current position.
/// </returns>
/// <remarks>
/// Doesn't change the current position.
/// </remarks>
public int IndexOf(byte value)
{
int start = Offset;
int absoluteIndex = _block.IndexOfUnchecked(value, start);
return (absoluteIndex >= 0) ? absoluteIndex - start : -1;
}

/// <summary>
/// Reads UTF8 encoded string starting at the current position.
/// </summary>
Expand Down
36 changes: 36 additions & 0 deletions src/System.Reflection.Metadata/tests/Utilities/BlobReaderTests.cs
Expand Up @@ -319,5 +319,41 @@ public unsafe void ReadFromMemoryBlock()
Assert.Equal(bytesRead, 0);
}
}

[Fact]
public unsafe void IndexOf()
{
byte[] buffer = new byte[]
{
0xF0, 0x90, 0x8D,
};

fixed (byte* bufferPtr = buffer)
{
var reader = new BlobReader(bufferPtr, buffer.Length);

Assert.Equal(0, reader.IndexOf(0xF0));
Assert.Equal(1, reader.IndexOf(0x90));
Assert.Equal(2, reader.IndexOf(0x8D));
Assert.Equal(-1, reader.IndexOf(0x8C));
Assert.Equal(-1, reader.IndexOf(0));
Assert.Equal(-1, reader.IndexOf(0xff));

reader.ReadByte();
Assert.Equal(-1, reader.IndexOf(0xF0));
Assert.Equal(0, reader.IndexOf(0x90));
Assert.Equal(1, reader.IndexOf(0x8D));

reader.ReadByte();
Assert.Equal(-1, reader.IndexOf(0xF0));
Assert.Equal(-1, reader.IndexOf(0x90));
Assert.Equal(0, reader.IndexOf(0x8D));

reader.ReadByte();
Assert.Equal(-1, reader.IndexOf(0xF0));
Assert.Equal(-1, reader.IndexOf(0x90));
Assert.Equal(-1, reader.IndexOf(0x8D));
}
}
}
}