Skip to content

Commit

Permalink
Optimize remainder
Browse files Browse the repository at this point in the history
  • Loading branch information
JamesNK committed Dec 16, 2020
1 parent 83bfa4c commit 21f9dd5
Showing 1 changed file with 11 additions and 7 deletions.
18 changes: 11 additions & 7 deletions csharp/src/Google.Protobuf/WritingPrimitives.cs
Expand Up @@ -179,8 +179,6 @@ public static void WriteString(ref Span<byte> buffer, ref WriterInternalState st
{
if (length == value.Length) // Must be all ASCII...
{
int currentIndex = 0;

// If 64bit, and value has at least 4 chars, process 4 chars at a time.
if (IntPtr.Size == 8 && value.Length >= 4)
{
Expand All @@ -190,6 +188,7 @@ public static void WriteString(ref Span<byte> buffer, ref WriterInternalState st
// Process 4 chars at a time until there are less than 4 remaining.
// We already know all characters are ASCII so there is no need to validate the source.
int lastIndexWhereCanReadFourChars = value.Length - 4;
int currentIndex = 0;
do
{
NarrowFourUtf16CharsToAsciiAndWriteToBuffer(
Expand All @@ -198,14 +197,19 @@ public static void WriteString(ref Span<byte> buffer, ref WriterInternalState st

} while ((currentIndex += 4) <= lastIndexWhereCanReadFourChars);

// Any chars remaining are processed in for loop below.
// Process remainder.
for (; currentIndex < length; currentIndex++)
{
Unsafe.AddByteOffset(ref destinationBytes, (IntPtr)currentIndex) = Unsafe.AddByteOffset(ref sourceBytes, (IntPtr)(currentIndex * 2));
}
}

for (int i = currentIndex; i < length; i++)
else
{
buffer[state.position + i] = (byte)value[i];
for (int i = 0; i < length; i++)
{
buffer[state.position + i] = (byte)value[i];
}
}

state.position += length;
}
else
Expand Down

0 comments on commit 21f9dd5

Please sign in to comment.