DotNext by .NET Foundation and Contributors

<PackageReference Include="DotNext" Version="4.1.0" />

 TextConsumer

Represents implementation of IReadOnlySpanConsumer<T> in the form of the writer to TextWriter.
using DotNext.Buffers; using System; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Threading; using System.Threading.Tasks; namespace DotNext.IO { [StructLayout(LayoutKind.Auto)] public readonly struct TextConsumer : IReadOnlySpanConsumer<char>, ISupplier<ReadOnlyMemory<char>, CancellationToken, ValueTask>, IFlushable { [System.Runtime.CompilerServices.Nullable(1)] private readonly TextWriter output; public bool IsEmpty => output == null; [System.Runtime.CompilerServices.NullableContext(1)] public TextConsumer(TextWriter output) { if (output == null) throw new ArgumentNullException("output"); this.output = output; } void IReadOnlySpanConsumer<char>.Invoke(ReadOnlySpan<char> input) { output.Write(input); } ValueTask ISupplier<ReadOnlyMemory<char>, CancellationToken, ValueTask>.Invoke(ReadOnlyMemory<char> input, CancellationToken token) { return new ValueTask(output.WriteAsync(input, token)); } void IFlushable.Flush() { output.Flush(); } [System.Runtime.CompilerServices.NullableContext(1)] Task IFlushable.FlushAsync(CancellationToken token) { if (!token.IsCancellationRequested) return output.FlushAsync(); return Task.FromCanceled(token); } public bool Equals(TextConsumer other) { return output == other.output; } [System.Runtime.CompilerServices.NullableContext(2)] public override bool Equals([NotNullWhen(true)] object other) { if (other is TextConsumer) { TextConsumer other2 = (TextConsumer)other; return Equals(other2); } return false; } public override int GetHashCode() { return RuntimeHelpers.GetHashCode(output); } [System.Runtime.CompilerServices.NullableContext(2)] public override string ToString() { return output?.ToString(); } public static implicit operator TextConsumer(TextWriter output) { return new TextConsumer(output); } public static bool operator ==(TextConsumer x, TextConsumer y) { return x.Equals(y); } public static bool operator !=(TextConsumer x, TextConsumer y) { return !x.Equals(y); } } }