Skip to content

Commit 21753cf

Browse files
optimiz3rstam
authored andcommitted
Improve '_id' comparisons so they are more general case:
1. Array.IndexOf is now avoided for any input < 4 bytes 2. Comparison of "_id" is now done using a single branch
1 parent 3ada50f commit 21753cf

File tree

1 file changed

+26
-9
lines changed

1 file changed

+26
-9
lines changed

Bson/IO/BsonBuffer.cs

Lines changed: 26 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -970,18 +970,35 @@ private static int TryParseCString(byte[] buffer, int startIndex, int length, ou
970970
return 1;
971971
}
972972

973-
// special case the _id string
974-
if (length >= 4 &&
975-
c1 == 0x5f && // '_'
976-
c2 == 0x69 && // 'i'
977-
buffer[startIndex + 2] == 0x64 && // 'd'
978-
buffer[startIndex + 3] == 0) // '/0'
979-
{
980-
value = "_id";
973+
if (length < 3)
974+
{
975+
value = null;
976+
return -1;
977+
}
978+
979+
var c3 = buffer[startIndex + 2];
980+
if (c3 == 0)
981+
{
982+
value = __utf8Encoding.GetString(buffer, startIndex, 2);
983+
return 2;
984+
}
985+
986+
if (length < 4)
987+
{
988+
value = null;
989+
return -1;
990+
}
991+
992+
if (buffer[startIndex + 3] == 0)
993+
{
994+
// special case the _id string
995+
// '_id'; 0x5f == '_', 0x69 == 'i', 0x64 == 'd'
996+
value = ((c1 | c2 << 8 | c3 << 16) == 0x64695f) ?
997+
"_id" : __utf8Encoding.GetString(buffer, startIndex, 3);
981998
return 3;
982999
}
9831000

984-
var index = Array.IndexOf<byte>(buffer, 0, startIndex + 2, length - 2);
1001+
var index = Array.IndexOf<byte>(buffer, 0, startIndex + 4, length - 4);
9851002
if (index != -1)
9861003
{
9871004
var stringLength = index - startIndex;

0 commit comments

Comments
 (0)