using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; namespace SharpGen.CppModel { public abstract class CppContainer : CppElement { private List items; public IReadOnlyList Items { get => (IReadOnlyList) items ?? ImmutableList.Empty; set => AdoptAllChildren( items = value switch { List list => list, _ => new List(value) } ); } protected internal virtual IEnumerable AllItems => Iterate(); public bool IsEmpty => items == null || items.Count == 0; protected CppContainer(string name) : base(name) { } public void Add(CppElement element) { AdoptChild(element); items ??= new List(); items.Add(element); } public void AddRange(IEnumerable elements) { items ??= new List(); var index = items.Count; items.AddRange(elements); var newCount = items.Count; for (var i = index; i < newCount; i++) AdoptChild(items[i]); } private void AdoptChild(CppElement element) { element.Parent?.items?.Remove(element); element.Parent = this; } private void AdoptAllChildren(IEnumerable elements) { foreach (var element in elements) AdoptChild(element); } internal void RemoveChild(CppElement child) => items?.Remove(child); /// /// Iterates on items on this instance. /// /// Type of the item to iterate /// An enumeration on items public IEnumerable Iterate() where T : CppElement => items == null ? Enumerable.Empty() : Items.OfType(); } }