namespace MemoryPools.Collections.Specialized { public static partial class AsSingleQueryList { private class EnumerableShared : IPoolingEnumerable where T : class { private PoolingListCanon _src; private int _count; public IPoolingEnumerable Init(PoolingListCanon src) { _src = src; _count = 0; return this; } public IPoolingEnumerator GetEnumerator() { _count++; return Pool.Get().Init(this, _src); } IPoolingEnumerator IPoolingEnumerable.GetEnumerator() => GetEnumerator(); private void Dispose() { if (_count == 0) return; _count--; if (_count == 0) { _src?.Dispose(); _src = default; Pool>.Return(this); } } private class EnumeratorRef : IPoolingEnumerator { private IPoolingEnumerator _enumerator; private EnumerableShared _parent; public IPoolingEnumerator Init(EnumerableShared parent, IPoolingEnumerable src) { _parent = parent; _enumerator = src.GetEnumerator(); return this; } public bool MoveNext() => _enumerator.MoveNext(); public void Reset() => _enumerator.Reset(); public T Current => _enumerator.Current; object IPoolingEnumerator.Current => Current; public void Dispose() { _enumerator?.Dispose(); _enumerator = default; _parent?.Dispose(); _parent = default; Pool.Return(this); } } } } }