public static void Serialize()

in src/Elastic.Transport/Components/Serialization/TransportSerializerExtensions.cs [210:257]


	public static void Serialize<T>(
		this Serializer serializer,
		T? data,
		Utf8JsonWriter writer,
		SerializationFormatting formatting = SerializationFormatting.None
	) => Serialize<T>(serializer, data, writer, TransportConfiguration.DefaultMemoryStreamFactory, formatting);

	/// <summary>
	/// Extension method that writes the serialized representation of an instance of <typeparamref name="T"/> to a
	/// <see cref="Utf8JsonWriter"/>.
	/// </summary>
	/// <typeparam name="T">The type of the data to be serialized.</typeparam>
	/// <param name="serializer"><inheritdoc cref="Serializer" path="/summary"/></param>
	/// <param name="data">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<T>(
		this Serializer serializer,
		T? data,
		Utf8JsonWriter writer,
		MemoryStreamFactory? memoryStreamFactory,
		SerializationFormatting formatting = SerializationFormatting.None)
	{
		if (serializer is SystemTextJsonSerializer stjSerializer && stjSerializer.SupportsFastPath(typeof(T)))
		{
			// When the serializer derives from `SystemTextJsonSerializer` we can avoid unnecessary allocations and
			// serialize straight into the writer.
			JsonSerializer.Serialize(writer, data, 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
	}