WriteFloat improvements

pull/7576/head
Jan Tattermusch 5 years ago
parent 1f56e5e2a4
commit d3557cab21
  1. 30
      csharp/src/Google.Protobuf/WritingPrimitives.cs

@ -64,7 +64,7 @@ namespace Google.Protobuf
public static unsafe void WriteFloat(ref Span<byte> buffer, ref WriterInternalState state, float value) public static unsafe void WriteFloat(ref Span<byte> buffer, ref WriterInternalState state, float value)
{ {
const int length = sizeof(float); const int length = sizeof(float);
if (state.limit - state.position >= length) if (buffer.Length - state.position >= length)
{ {
// if there's enough space in the buffer, write the float directly into the buffer // if there's enough space in the buffer, write the float directly into the buffer
var floatSpan = buffer.Slice(state.position, length); var floatSpan = buffer.Slice(state.position, length);
@ -78,19 +78,27 @@ namespace Google.Protobuf
} }
else else
{ {
Span<byte> floatSpan = stackalloc byte[length]; WriteFloatSlowPath(ref buffer, ref state, value);
Unsafe.WriteUnaligned(ref MemoryMarshal.GetReference(floatSpan), value); }
}
if (!BitConverter.IsLittleEndian) [MethodImpl(MethodImplOptions.NoInlining)]
{ private static unsafe void WriteFloatSlowPath(ref Span<byte> buffer, ref WriterInternalState state, float value)
floatSpan.Reverse(); {
} const int length = sizeof(float);
WriteRawByte(ref buffer, ref state, floatSpan[0]); // TODO(jtattermusch): deduplicate the code. Populating the span is the same as for the fastpath.
WriteRawByte(ref buffer, ref state, floatSpan[1]); Span<byte> floatSpan = stackalloc byte[length];
WriteRawByte(ref buffer, ref state, floatSpan[2]); Unsafe.WriteUnaligned(ref MemoryMarshal.GetReference(floatSpan), value);
WriteRawByte(ref buffer, ref state, floatSpan[3]); if (!BitConverter.IsLittleEndian)
{
floatSpan.Reverse();
} }
WriteRawByte(ref buffer, ref state, floatSpan[0]);
WriteRawByte(ref buffer, ref state, floatSpan[1]);
WriteRawByte(ref buffer, ref state, floatSpan[2]);
WriteRawByte(ref buffer, ref state, floatSpan[3]);
} }
/// <summary> /// <summary>

Loading…
Cancel
Save