WriteFloat improvements

pull/7576/head
Jan Tattermusch 5 years ago
parent 1f56e5e2a4
commit d3557cab21
  1. 14
      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,9 +78,18 @@ namespace Google.Protobuf
} }
else else
{ {
WriteFloatSlowPath(ref buffer, ref state, value);
}
}
[MethodImpl(MethodImplOptions.NoInlining)]
private static unsafe void WriteFloatSlowPath(ref Span<byte> buffer, ref WriterInternalState state, float value)
{
const int length = sizeof(float);
// TODO(jtattermusch): deduplicate the code. Populating the span is the same as for the fastpath.
Span<byte> floatSpan = stackalloc byte[length]; Span<byte> floatSpan = stackalloc byte[length];
Unsafe.WriteUnaligned(ref MemoryMarshal.GetReference(floatSpan), value); Unsafe.WriteUnaligned(ref MemoryMarshal.GetReference(floatSpan), value);
if (!BitConverter.IsLittleEndian) if (!BitConverter.IsLittleEndian)
{ {
floatSpan.Reverse(); floatSpan.Reverse();
@ -91,7 +100,6 @@ namespace Google.Protobuf
WriteRawByte(ref buffer, ref state, floatSpan[2]); WriteRawByte(ref buffer, ref state, floatSpan[2]);
WriteRawByte(ref buffer, ref state, floatSpan[3]); WriteRawByte(ref buffer, ref state, floatSpan[3]);
} }
}
/// <summary> /// <summary>
/// Writes a uint64 field value, without a tag, to the stream. /// Writes a uint64 field value, without a tag, to the stream.

Loading…
Cancel
Save