Skip to content

Commit 464bf09

Browse files
author
Stefán J. Sigurðarson
committed
Removing unsafe code for netcoreapp targets.
1 parent 91b5ae3 commit 464bf09

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed

projects/RabbitMQ.Client/client/impl/WireFormatting.cs

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -168,6 +168,10 @@ public static int ReadShortstr(ReadOnlySpan<byte> span, out string value)
168168
// equals span.Length >= byteCount + 1
169169
if (span.Length > byteCount)
170170
{
171+
#if NETCOREAPP
172+
value = Encoding.UTF8.GetString(span.Slice(1, byteCount));
173+
return 1 + byteCount;
174+
#else
171175
unsafe
172176
{
173177
fixed (byte* bytes = &MemoryMarshal.GetReference(span.Slice(1)))
@@ -176,6 +180,7 @@ public static int ReadShortstr(ReadOnlySpan<byte> span, out string value)
176180
return 1 + byteCount;
177181
}
178182
}
183+
#endif
179184
}
180185

181186
throw new ArgumentOutOfRangeException("span", $"Span has not enough space ({span.Length} instead of {byteCount + 1})");
@@ -725,6 +730,18 @@ public static int WriteShortstr(Span<byte> span, string val)
725730
maxLength = byte.MaxValue;
726731
}
727732

733+
#if NETCOREAPP
734+
try
735+
{
736+
int bytesWritten = Encoding.UTF8.GetBytes(val, span.Slice(1));
737+
span[0] = (byte)bytesWritten;
738+
return bytesWritten + 1;
739+
}
740+
catch (ArgumentException e)
741+
{
742+
throw new ArgumentOutOfRangeException($"Value exceeds the maximum allowed length of {maxLength} bytes.", e);
743+
}
744+
#else
728745
unsafe
729746
{
730747
fixed (char* chars = val)
@@ -742,6 +759,7 @@ public static int WriteShortstr(Span<byte> span, string val)
742759
}
743760
}
744761
}
762+
#endif
745763
}
746764

747765
[MethodImpl(MethodImplOptions.AggressiveInlining)]
@@ -753,6 +771,11 @@ public static int WriteLongstr(Span<byte> span, string val)
753771
return 4;
754772
}
755773

774+
#if NETCOREAPP
775+
int bytesWritten = Encoding.UTF8.GetBytes(val, span.Slice(4));
776+
NetworkOrderSerializer.WriteUInt32(span, (uint)bytesWritten);
777+
return bytesWritten + 4;
778+
#else
756779
unsafe
757780
{
758781
fixed (char* chars = val)
@@ -763,6 +786,7 @@ public static int WriteLongstr(Span<byte> span, string val)
763786
return bytesWritten + 4;
764787
}
765788
}
789+
#endif
766790
}
767791

768792
public static int WriteTable(Span<byte> span, IDictionary val)

0 commit comments

Comments
 (0)