using System;
using System.Collections;
using System.Collections.Generic;
namespace Capnp
{
///
/// SerializerState specialization for List(T) when T is unknown (generic), List(Data), List(Text), and List(List(...)).
///
/// SerializerState which represents the element type
public class ListOfPointersSerializer:
SerializerState,
IReadOnlyList
where TS: SerializerState, new()
{
///
/// Gets or sets the element at given index.
///
/// Element index
/// Serializer state representing the desired element
/// List was not initialized, or attempting to overwrite a non-null element.
/// is out of range.
public TS this[int index]
{
get
{
if (!IsAllocated)
throw new InvalidOperationException("Not initialized");
if (index < 0 || index >= Count)
throw new IndexOutOfRangeException();
return BuildPointer(index);
}
set
{
if (!IsAllocated)
throw new InvalidOperationException("Not initialized");
if (index < 0 || index >= Count)
throw new IndexOutOfRangeException();
Link(index, value, true);
}
}
///
/// This list's element count.
///
public int Count => ListElementCount;
IEnumerable Enumerate()
{
int count = Count;
for (int i = 0; i < count; i++)
{
yield return TryGetPointer(i);
}
}
///
/// Implements .
///
public IEnumerator GetEnumerator()
{
return Enumerate().GetEnumerator();
}
///
/// Initializes this list with a specific size. The list can be initialized only once.
///
/// List element count
/// The list was already initialized
/// is negative or greater than 2^29-1
public void Init(int count)
{
if (IsAllocated)
throw new InvalidOperationException("Already initialized");
if (count < 0)
throw new ArgumentOutOfRangeException(nameof(count));
SetListOfPointers(count);
}
///
/// 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();
}
}
}