namespace Python.Runtime.Codecs
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
///
/// Represents a group of s. Useful to group them by priority.
///
public sealed class EncoderGroup: IPyObjectEncoder, IEnumerable, IDisposable
{
readonly List encoders = new();
///
/// Add specified encoder to the group
///
public void Add(IPyObjectEncoder item)
{
if (item is null) throw new ArgumentNullException(nameof(item));
this.encoders.Add(item);
}
///
/// Remove all encoders from the group
///
public void Clear() => this.encoders.Clear();
///
public bool CanEncode(Type type) => this.encoders.Any(encoder => encoder.CanEncode(type));
///
public PyObject? TryEncode(object value)
{
if (value is null) throw new ArgumentNullException(nameof(value));
foreach (var encoder in this.GetEncoders(value.GetType()))
{
var result = encoder.TryEncode(value);
if (result != null)
{
return result;
}
}
return null;
}
///
public IEnumerator GetEnumerator() => this.encoders.GetEnumerator();
IEnumerator IEnumerable.GetEnumerator() => this.encoders.GetEnumerator();
public void Dispose()
{
foreach (var encoder in this.encoders.OfType())
{
encoder.Dispose();
}
this.encoders.Clear();
}
}
public static class EncoderGroupExtensions
{
///
/// Gets specific instances of
/// (potentially selecting one from a collection),
/// that can encode the specified .
///
public static IEnumerable GetEncoders(this IPyObjectEncoder decoder, Type type)
{
if (decoder is null) throw new ArgumentNullException(nameof(decoder));
if (decoder is IEnumerable composite)
{
foreach (var nestedEncoder in composite)
foreach (var match in nestedEncoder.GetEncoders(type))
{
yield return match;
}
} else if (decoder.CanEncode(type))
{
yield return decoder;
}
}
}
}