in src/Elastic.Transport/Components/Serialization/TransportSerializerExtensions.cs [268:317]
public static void Serialize(
this Serializer serializer,
object? data,
Type type,
Utf8JsonWriter writer,
SerializationFormatting formatting = SerializationFormatting.None
) => Serialize(serializer, data, type, writer, TransportConfiguration.DefaultMemoryStreamFactory, formatting);
/// <summary>
/// Extension method that writes the serialized representation of the given <paramref name="data"/> to a
/// <see cref="Utf8JsonWriter"/>.
/// </summary>
/// <param name="serializer"><inheritdoc cref="Serializer" path="/summary"/></param>
/// <param name="data">The data to serialize.</param>
/// <param name="type">The type of the data to serialize.</param>
/// <param name="writer">The destination <see cref="Utf8JsonWriter"/>.</param>
/// <param name="memoryStreamFactory">
/// A factory yielding <see cref="MemoryStream"/> instances, defaults to <see cref="RecyclableMemoryStreamFactory"/>
/// that yields memory streams backed by pooled byte arrays.
/// </param>
/// <param name="formatting"><inheritdoc cref="SerializationFormatting" path="/summary"/></param>
public static void Serialize(
this Serializer serializer,
object? data,
Type type,
Utf8JsonWriter writer,
MemoryStreamFactory? memoryStreamFactory,
SerializationFormatting formatting = SerializationFormatting.None)
{
if (serializer is SystemTextJsonSerializer stjSerializer && stjSerializer.SupportsFastPath(type))
{
// When the serializer derives from `SystemTextJsonSerializer` we can avoid unnecessary allocations and
// serialize straight into the writer.
JsonSerializer.Serialize(writer, data, type, stjSerializer.GetJsonSerializerOptions(formatting));
return;
}
memoryStreamFactory ??= TransportConfiguration.DefaultMemoryStreamFactory;
using var ms = memoryStreamFactory.Create();
serializer.Serialize(data, ms);
ms.Position = 0;
#if NET6_0_OR_GREATER
writer.WriteRawValue(ms.GetBuffer().AsSpan()[..(int)ms.Length], true);
#else
using var document = JsonDocument.Parse(ms);
document.RootElement.WriteTo(writer);
#endif
}