using System; using System.Collections; using System.Collections.Generic; namespace Capnp { /// /// SerializerState specialization for List(Text) /// public class ListOfTextSerializer : SerializerState, IReadOnlyList { /// /// Gets or sets the text at given index. Once an element is set, it cannot be overwritten. /// /// Element index /// List is not initialized /// is out of range. /// UTF-8 encoding exceeds 2^29-2 bytes public string? this[int index] { get { ListSerializerHelper.EnsureAllocated(this); if (index < 0 || index >= Count) throw new IndexOutOfRangeException(); return ReadText(index); } set { ListSerializerHelper.EnsureAllocated(this); if (index < 0 || index >= Count) throw new IndexOutOfRangeException(); WriteText(index, value); } } /// /// This list's element count. /// public int Count => ListElementCount; IEnumerable Enumerate() { int count = Count; for (int i = 0; i < count; i++) { yield return this[i]; } } /// /// Implementation of /> /// 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. /// /// List content. Can be null in which case the list is simply not initialized. /// The list was already initialized /// More than 2^29-1 items, or the UTF-8 encoding of an individual string requires more than 2^29-2 bytes. public void Init(IReadOnlyList? items) { if (items == null) { return; } Init(items.Count); for (int i = 0; i < items.Count; i++) { this[i] = items[i]; } } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } }