IEnumerableWithAddMethodConverter<TCollection>
sealed class IEnumerableWithAddMethodConverter<TCollection> : IEnumerableDefaultConverter<TCollection, object> where TCollection : IEnumerable
using System.Collections;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace System.Text.Json.Serialization.Converters
{
internal sealed class IEnumerableWithAddMethodConverter<TCollection> : IEnumerableDefaultConverter<TCollection, object> where TCollection : IEnumerable
{
protected override void Add([In] [IsReadOnly] object value, ref ReadStack state)
{
Action<TCollection, object> action = (Action<TCollection, object>)state.Current.JsonClassInfo.AddMethodDelegate;
action((TCollection)state.Current.ReturnValue, value);
}
protected override void CreateCollection(ref Utf8JsonReader reader, ref ReadStack state, JsonSerializerOptions options)
{
JsonClassInfo jsonClassInfo = state.Current.JsonClassInfo;
JsonClassInfo.ConstructorDelegate createObject = jsonClassInfo.CreateObject;
if (createObject == null)
ThrowHelper.ThrowNotSupportedException_CannotPopulateCollection(TypeToConvert, ref reader, ref state);
state.Current.ReturnValue = createObject();
if (jsonClassInfo.AddMethodDelegate == null)
jsonClassInfo.AddMethodDelegate = options.MemberAccessorStrategy.CreateAddMethodDelegate<TCollection>();
}
protected override bool OnWriteResume(Utf8JsonWriter writer, TCollection value, JsonSerializerOptions options, ref WriteStack state)
{
IEnumerator enumerator;
if (state.Current.CollectionEnumerator == null) {
enumerator = value.GetEnumerator();
if (!enumerator.MoveNext())
return true;
} else
enumerator = state.Current.CollectionEnumerator;
JsonConverter<object> elementConverter = IEnumerableDefaultConverter<TCollection, object>.GetElementConverter(ref state);
do {
if (ShouldFlush(writer, ref state)) {
state.Current.CollectionEnumerator = enumerator;
return false;
}
object value2 = enumerator.Current;
if (!elementConverter.TryWrite(writer, ref value2, options, ref state)) {
state.Current.CollectionEnumerator = enumerator;
return false;
}
} while (enumerator.MoveNext());
return true;
}
}
}