using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
namespace Capnp
{
///
/// SerializerState specialization for List(T) when T is a known struct (i.e. a list of fixed-width composites).
///
/// SerializerState which represents the struct type
public class ListOfStructsSerializer :
SerializerState,
IReadOnlyList
where TS : SerializerState, new()
{
///
/// Returns the struct serializer a given index.
///
/// Element index
/// The struct serializer
public TS this[int index]
{
get
{
if (!IsAllocated)
throw new InvalidOperationException("Not initialized");
if (index < 0 || index >= Count)
throw new IndexOutOfRangeException();
return ListBuildStruct(index);
}
}
///
/// This list's element count.
///
public int Count => ListElementCount;
///
/// Implementation of />
///
///
public IEnumerator GetEnumerator()
{
if (Count == 0) return Enumerable.Empty().GetEnumerator();
return ListEnumerateStructs().GetEnumerator();
}
///
/// Initializes this list with a specific size. The list can be initialized only once.
///
/// List element count
public void Init(int count)
{
if (IsAllocated)
throw new InvalidOperationException("Already initialized");
if (count < 0)
throw new ArgumentOutOfRangeException(nameof(count));
var sample = new TS();
SetListOfStructs(count, sample.StructDataCount, sample.StructPtrCount);
}
///
/// Initializes the list with given content.
///
/// Item type
/// List content. Can be null in which case the list is simply not initialized.
/// Serialization action to transfer a particular item into the serializer state.
/// The list was already initialized
/// More than 2^29-1 items.
public void Init(IReadOnlyList? items, Action init)
{
if (items == null)
{
return;
}
Init(items.Count);
for (int i = 0; i < items.Count; i++)
{
init(this[i], items[i]);
}
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
}