StreamIter.cs (3081B)
1 using Std.Maybe; 2 using Std.Num; 3 using Std.Ops; 4 using Std.Result; 5 using System; 6 using System.IO; 7 #region Namespaces 8 namespace Std.Iter { 9 #region Types 10 public readonly struct StreamIter<TStream>: IFusedIterator<ReadOnlyMemory<byte>> where TStream: notnull, Stream { 11 12 #region Type-level Constructors 13 #endregion 14 15 #region Instance Constructors 16 public StreamIter() => throw new InvalidOperationException("Parameterless constructor is not allowed to be called."); 17 StreamIter(TStream stream, byte[] buffer) => (_stream, _buffer) = (stream, buffer); 18 #endregion 19 20 #region Type-level Fields 21 #endregion 22 23 #region Instance Fields 24 readonly Stream _stream; 25 readonly byte[] _buffer; 26 #endregion 27 28 #region Type-level Properties 29 #endregion 30 31 #region Instance Properties 32 public readonly NonZeroUint BufferCapacity => NonZeroUint.NewUnsafe((uint)_buffer.Length); 33 #endregion 34 35 #region Type-level Functions 36 public static Maybe<StreamIter<TStream>> New(TStream stream, NonZeroUint bufferCap) => stream.CanRead ? new(new StreamIter<TStream>(stream, new byte[(int)bufferCap.IntoUint()])) : Maybe<StreamIter<TStream>>.None(); 37 public static Maybe<StreamIter<TStream>> New(TStream stream, byte[] buffer) => stream.CanRead && buffer.Length > 0 ? new(new StreamIter<TStream>(stream, buffer)) : Maybe<StreamIter<TStream>>.None(); 38 #endregion 39 40 #region Instance Functions 41 public readonly Result<Unit, ulong> AdvanceBy(ulong n) => IIterator<ReadOnlyMemory<byte>>.AdvanceByDefault(this, n); 42 public readonly ulong Count() => IIterator<ReadOnlyMemory<byte>>.CountDefault(this); 43 public override readonly bool Equals(object? _) => false; 44 public readonly TInit Fold<TInit>(TInit init, Fn<TInit, ReadOnlyMemory<byte>, TInit> f) where TInit: notnull => IIterator<ReadOnlyMemory<byte>>.FoldDefault(this, init, f); 45 public override readonly int GetHashCode() => 0; 46 public readonly Maybe<ReadOnlyMemory<byte>> Last() => IIterator<ReadOnlyMemory<byte>>.LastDefault(this); 47 public readonly Maybe<ReadOnlyMemory<byte>> Next() { 48 49 var count = _stream.Read(_buffer.AsSpan()); 50 return count == 0 ? Maybe<ReadOnlyMemory<byte>>.None() : new(_buffer.AsMemory(0, count)); 51 } 52 public readonly ReadOnlySpan<byte> NextSpan() => _buffer.AsSpan(0, _stream.Read(_buffer.AsSpan())); 53 public readonly Prod<ulong, Maybe<ulong>> SizeHint() => new(ulong.MinValue, Maybe<ulong>.None()); 54 public override readonly string ToString() => string.Empty; 55 public readonly Result<TInit, TErr> TryFold<TInit, TErr>(TInit init, Fn<TInit, ReadOnlyMemory<byte>, Result<TInit, TErr>> f) where TInit: notnull where TErr: notnull => IIterator<ReadOnlyMemory<byte>>.TryFoldDefault(this, init, f); 56 #endregion 57 58 #region Operators 59 #endregion 60 61 #region Types 62 #endregion 63 } 64 #endregion 65 66 #region Namespaces 67 #endregion 68 } 69 #endregion