private unsafe void TestComparisons(string heapValue, int offset, string value, bool unicode = false) { byte[] heap; MetadataStringDecoder decoder = MetadataStringDecoder.DefaultUTF8; fixed (byte* heapPtr = (heap = Encoding.UTF8.GetBytes(heapValue))) { var block = new MemoryBlock(heapPtr, heap.Length); string heapSubstr = GetStringHeapValue(heapValue, offset); // compare: if (!unicode) { int actualCmp = block.CompareUtf8NullTerminatedStringWithAsciiString(offset, value); int expectedCmp = StringComparer.Ordinal.Compare(heapSubstr, value); Assert.Equal(Math.Sign(expectedCmp), Math.Sign(actualCmp)); } // equals: bool actualEq = block.Utf8NullTerminatedEquals(offset, value, decoder); bool expectedEq = StringComparer.Ordinal.Equals(heapSubstr, value); Assert.Equal(expectedEq, actualEq); // starts with: bool actualSW = block.Utf8NullTerminatedStartsWith(offset, value, decoder); bool expectedSW = heapSubstr.StartsWith(value, StringComparison.Ordinal); Assert.Equal(actualSW, expectedSW); } }
public unsafe void ComparisonToInvalidByteSequenceMatchesFallback() { MetadataStringDecoder decoder = MetadataStringDecoder.DefaultUTF8; // dangling lead byte byte[] buffer; fixed (byte* ptr = (buffer = new byte[] { 0xC0 })) { var block = new MemoryBlock(ptr, buffer.Length); Assert.False(block.Utf8NullTerminatedStartsWith(0, new string((char)0xC0, 1), decoder)); Assert.False(block.Utf8NullTerminatedEquals(0, new string((char)0xC0, 1), decoder)); Assert.True(block.Utf8NullTerminatedStartsWith(0, "\uFFFD", decoder)); Assert.True(block.Utf8NullTerminatedEquals(0, "\uFFFD", decoder)); } // overlong encoding fixed (byte* ptr = (buffer = new byte[] { (byte)'a', 0xC0, 0xAF, (byte)'b', 0x0 })) { var block = new MemoryBlock(ptr, buffer.Length); Assert.False(block.Utf8NullTerminatedStartsWith(0, "a\\", decoder)); Assert.False(block.Utf8NullTerminatedEquals(0, "a\\b", decoder)); Assert.True(block.Utf8NullTerminatedStartsWith(0, "a\uFFFD", decoder)); Assert.True(block.Utf8NullTerminatedEquals(0, "a\uFFFD\uFFFDb", decoder)); } }
private static unsafe void TestComparison(MemoryBlock block, int offset, string value, string heapSubstr, MetadataStringDecoder decoder, bool ignoreCase) { // equals: bool actualEq = block.Utf8NullTerminatedEquals(offset, value, decoder, terminator: '\0', ignoreCase: ignoreCase); bool expectedEq = string.Equals(heapSubstr, value, ignoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal); Assert.Equal(expectedEq, actualEq); // starts with: bool actualSW = block.Utf8NullTerminatedStartsWith(offset, value, decoder, terminator: '\0', ignoreCase: ignoreCase); bool expectedSW = heapSubstr.StartsWith(value, ignoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal); Assert.Equal(actualSW, expectedSW); }