Skip to content

Commit

Permalink
Avoid pinning when decoding long strings
Browse files Browse the repository at this point in the history
  • Loading branch information
Havret committed Apr 17, 2024
1 parent 370c249 commit 08de809
Showing 1 changed file with 12 additions and 13 deletions.
25 changes: 12 additions & 13 deletions src/ArtemisNetCoreClient/ArtemisBinaryConverter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -145,24 +145,23 @@ public static int ReadString(in ReadOnlySpan<byte> source, out string value)
else
{
readBytes += ReadInt32(source[readBytes..], out var byteCount);

unsafe
{
fixed(void* ptr = &MemoryMarshal.GetReference(source.Slice(readBytes, byteCount)))
ref var reference = ref MemoryMarshal.GetReference(source.Slice(readBytes, byteCount));
var ptr = Unsafe.AsPointer(ref reference);
value = string.Create(byteCount >> 1, (ptr: (IntPtr) ptr, byteCount), static (span, state) =>
{
value = string.Create(byteCount >> 1, (ptr: (IntPtr) ptr, byteCount), static (span, state) =>
var source = new Span<byte>(state.ptr.ToPointer(), state.byteCount);
for (var i = 0; i < state.byteCount; i += 2)
{
var source = new Span<byte>(state.ptr.ToPointer(), state.byteCount);
for (var i = 0; i < state.byteCount; i += 2)
{
var lowByte = source[i];
var highByte = source[i + 1];
span[i >> 1] = (char) (lowByte | (highByte << 8));
}
});
}
var lowByte = source[i];
var highByte = source[i + 1];
span[i >> 1] = (char) (lowByte | (highByte << 8));
}
});
}
readBytes+= byteCount;

readBytes += byteCount;
}

return readBytes;
Expand Down

0 comments on commit 08de809

Please sign in to comment.