csharp: use span-based ToBase64 in ByteString (#16976)

With .NET 5+, a copy can be avoided when the memory is not an array.

Closes #16976

COPYBARA_INTEGRATE_REVIEW=https://github.com/protocolbuffers/protobuf/pull/16976 from verdie-g:main fd4f5aeee4
PiperOrigin-RevId: 638968774
pull/16971/head
Grégoire 6 months ago committed by Copybara-Service
parent c12c73212d
commit efaaeba6a8
  1. 4
      csharp/src/Google.Protobuf/ByteString.cs

@ -117,6 +117,9 @@ namespace Google.Protobuf
/// <returns>A base64 representation of this <c>ByteString</c>.</returns>
public string ToBase64()
{
#if NET5_0_OR_GREATER
return Convert.ToBase64String(bytes.Span);
#else
if (MemoryMarshal.TryGetArray(bytes, out ArraySegment<byte> segment))
{
// Fast path. ByteString was created with an array, so pass the underlying array.
@ -127,6 +130,7 @@ namespace Google.Protobuf
// Slow path. BytesString is not an array. Convert memory and pass result to ToBase64String.
return Convert.ToBase64String(bytes.ToArray());
}
#endif
}
/// <summary>

Loading…
Cancel
Save