Enumerate.cs (3226B)
1 using Std.Convert; 2 using Std.Maybe; 3 using Std.Ops; 4 using Std.Result; 5 using System; 6 using System.Runtime.InteropServices; 7 #region Namespaces 8 namespace Std.Iter { 9 #region Types 10 [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode, Pack = 0)] 11 public struct Enumerate<T, TIter>: IInto<Enumerate<T, TIter>>, IIterator<Prod<ulong, T>> where T: notnull where TIter: notnull, IIterator<T> { 12 13 #region Type-level Constructors 14 #endregion 15 16 #region Instance Constructors 17 public Enumerate() => throw new InvalidOperationException("Parameterless constructor is not allowed to be called!"); 18 internal Enumerate(TIter iter) => (_iter, _count) = (iter, ulong.MinValue); 19 #endregion 20 21 #region Type-level Fields 22 #endregion 23 24 #region Instance Fields 25 ulong _count; 26 [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Can't be readonly since we call mutable methods on it.")] 27 TIter _iter; 28 #endregion 29 30 #region Type-level Properties 31 #endregion 32 33 #region Instance Properties 34 #endregion 35 36 #region Type-level Functions 37 #endregion 38 39 #region Instance Functions 40 public Result<Unit, ulong> AdvanceBy(ulong n) { 41 42 var res = _iter.AdvanceBy(n); 43 44 if (res.IsErr) { 45 return res; 46 } else { 47 _count += n; 48 return res; 49 } 50 } 51 public ulong Count() => _iter.Count(); 52 public override readonly bool Equals(object? _) => false; 53 public TInit Fold<TInit>(TInit init, Fn<TInit, Prod<ulong, T>, TInit> f) where TInit: notnull { 54 55 static Fn<TInit, T, TInit> enumer(ulong count, Fn<TInit, Prod<ulong, T>, TInit> fold) => (acc, item) => { acc = fold(acc, new(count, item)); count += 1ul; return acc; }; 56 return _iter.Fold(init, enumer(_count, f)); 57 } 58 public override readonly int GetHashCode() => 0; 59 public readonly Enumerate<T, TIter> Into() => this; 60 public Maybe<Prod<ulong, T>> Last() => IIterator<Prod<ulong, T>>.LastDefault(ref this); 61 public Maybe<Prod<ulong, T>> Next() { 62 63 var mbe = _iter.Next(); 64 return mbe.IsNone ? Maybe<Prod<ulong, T>>.None() : Maybe<Prod<ulong, T>>.Some(new(_count++, mbe._some)); 65 } 66 public Prod<ulong, Maybe<ulong>> SizeHint() => _iter.SizeHint(); 67 public override readonly string ToString() => string.Empty; 68 public Result<TInit, TErr> TryFold<TInit, TErr>(TInit init, Fn<TInit, Prod<ulong, T>, Result<TInit, TErr>> f) where TInit: notnull where TErr: notnull { 69 70 var count = _count; 71 var res = _iter.TryFold(init, (acc, item) => { var res = f(acc, new(count, item)); count += 1ul; return res; }); 72 _count = count; 73 return res; 74 } 75 readonly Result<Enumerate<T, TIter>, Bottom> ITryInto<Enumerate<T, TIter>, Bottom>.TryInto() => new(this); 76 #endregion 77 78 #region Operators 79 #endregion 80 81 #region Types 82 #endregion 83 } 84 #endregion 85 86 #region Namespaces 87 #endregion 88 } 89 #endregion