Skip to content

Commit

Permalink
Implements BlobReader.IndexOf(byte) (dotnet/corefx#12308)
Browse files Browse the repository at this point in the history
Commit migrated from dotnet/corefx@958ca51
  • Loading branch information
tmat committed Oct 3, 2016
1 parent c9f1a4a commit e586b39
Show file tree
Hide file tree
Showing 3 changed files with 56 additions and 0 deletions.
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 @@ -345,6 +345,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
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));
}
}
}
}

0 comments on commit e586b39

Please sign in to comment.