commit 1e9844143c02ad75f879e0a1754ec21b58d6a831 Author: Phil Gilmore Date: Thu May 15 13:27:49 2025 -0600 Initial commit. diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..28764cf --- /dev/null +++ b/.editorconfig @@ -0,0 +1,34 @@ +root=true + +[{*, *.*}] +resharper_tabs_are_disallowed_highlighting=none + +[*.cs] +tab_width = 4 +indent_size = 4 +indent_style = tab + +[{*.vb, *.bas}] +tab_width = 4 +indent_size = 4 +indent_style = tab + +[*.xml] +tab_width = 4 +indent_size = 4 +indent_style = tab + +[*.py] +tab_width = 4 +indent_size = 4 +indent_style = tab + +[{*.yml, *.yaml}] +tab_width = 2 +indent_size = 2 +indent_style = space + +[*.pas] +tab_width = 2 +indent_size = 2 +indent_style = space diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..015e5fd --- /dev/null +++ b/.gitignore @@ -0,0 +1,399 @@ +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. +## +## Get latest from https://github.com/github/gitignore/blob/main/VisualStudio.gitignore + +# User-specific files +*.rsuser +*.suo +*.user +*.userosscache +*.sln.docstates + +# User-specific files (MonoDevelop/Xamarin Studio) +*.userprefs + +# Mono auto generated files +mono_crash.* + +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +x64/ +x86/ +[Ww][Ii][Nn]32/ +[Aa][Rr][Mm]/ +[Aa][Rr][Mm]64/ +bld/ +[Bb]in/ +[Oo]bj/ +[Ll]og/ +[Ll]ogs/ + +# Visual Studio 2015/2017 cache/options directory +.vs/ +# Uncomment if you have tasks that create the project's static files in wwwroot +#wwwroot/ + +# Visual Studio 2017 auto generated files +Generated\ Files/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +# NUnit +*.VisualState.xml +TestResult.xml +nunit-*.xml + +# Build Results of an ATL Project +[Dd]ebugPS/ +[Rr]eleasePS/ +dlldata.c + +# Benchmark Results +BenchmarkDotNet.Artifacts/ + +# .NET Core +project.lock.json +project.fragment.lock.json +artifacts/ + +# ASP.NET Scaffolding +ScaffoldingReadMe.txt + +# StyleCop +StyleCopReport.xml + +# Files built by Visual Studio +*_i.c +*_p.c +*_h.h +*.ilk +*.meta +*.obj +*.iobj +*.pch +*.pdb +*.ipdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*_wpftmp.csproj +*.log +*.tlog +*.vspscc +*.vssscc +.builds +*.pidb +*.svclog +*.scc + +# Chutzpah Test files +_Chutzpah* + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opendb +*.opensdf +*.sdf +*.cachefile +*.VC.db +*.VC.VC.opendb + +# Visual Studio profiler +*.psess +*.vsp +*.vspx +*.sap + +# Visual Studio Trace Files +*.e2e + +# TFS 2012 Local Workspace +$tf/ + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper +*.DotSettings.user + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# AxoCover is a Code Coverage Tool +.axoCover/* +!.axoCover/settings.json + +# Coverlet is a free, cross platform Code Coverage Tool +coverage*.json +coverage*.xml +coverage*.info + +# Visual Studio code coverage results +*.coverage +*.coveragexml + +# NCrunch +_NCrunch_* +.*crunch*.local.xml +nCrunchTemp_* + +# MightyMoose +*.mm.* +AutoTest.Net/ + +# Web workbench (sass) +.sass-cache/ + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.[Pp]ublish.xml +*.azurePubxml +# Note: Comment the next line if you want to checkin your web deploy settings, +# but database connection strings (with potential passwords) will be unencrypted +*.pubxml +*.publishproj + +# Microsoft Azure Web App publish settings. Comment the next line if you want to +# checkin your Azure Web App publish settings, but sensitive information contained +# in these scripts will be unencrypted +PublishScripts/ + +# NuGet Packages +*.nupkg +# NuGet Symbol Packages +*.snupkg +# The packages folder can be ignored because of Package Restore +**/[Pp]ackages/* +# except build/, which is used as an MSBuild target. +!**/[Pp]ackages/build/ +# Uncomment if necessary however generally it will be regenerated when needed +#!**/[Pp]ackages/repositories.config +# NuGet v3's project.json files produces more ignorable files +*.nuget.props +*.nuget.targets + +# Microsoft Azure Build Output +csx/ +*.build.csdef + +# Microsoft Azure Emulator +ecf/ +rcf/ + +# Windows Store app package directories and files +AppPackages/ +BundleArtifacts/ +Package.StoreAssociation.xml +_pkginfo.txt +*.appx +*.appxbundle +*.appxupload + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!?*.[Cc]ache/ + +# Others +ClientBin/ +~$* +*~ +*.dbmdl +*.dbproj.schemaview +*.jfm +*.pfx +*.publishsettings +orleans.codegen.cs + +# Including strong name files can present a security risk +# (https://github.com/github/gitignore/pull/2483#issue-259490424) +#*.snk + +# Since there are multiple workflows, uncomment next line to ignore bower_components +# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) +#bower_components/ + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file +# to a newer Visual Studio version. Backup files are not needed, +# because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm +ServiceFabricBackup/ +*.rptproj.bak + +# SQL Server files +*.mdf +*.ldf +*.ndf + +# Business Intelligence projects +*.rdl.data +*.bim.layout +*.bim_*.settings +*.rptproj.rsuser +*- [Bb]ackup.rdl +*- [Bb]ackup ([0-9]).rdl +*- [Bb]ackup ([0-9][0-9]).rdl + +# Microsoft Fakes +FakesAssemblies/ + +# GhostDoc plugin setting file +*.GhostDoc.xml + +# Node.js Tools for Visual Studio +.ntvs_analysis.dat +node_modules/ + +# Visual Studio 6 build log +*.plg + +# Visual Studio 6 workspace options file +*.opt + +# Visual Studio 6 auto-generated workspace file (contains which files were open etc.) +*.vbw + +# Visual Studio 6 auto-generated project file (contains which files were open etc.) +*.vbp + +# Visual Studio 6 workspace and project file (working project files containing files to include in project) +*.dsw +*.dsp + +# Visual Studio 6 technical files +*.ncb +*.aps + +# Visual Studio LightSwitch build output +**/*.HTMLClient/GeneratedArtifacts +**/*.DesktopClient/GeneratedArtifacts +**/*.DesktopClient/ModelManifest.xml +**/*.Server/GeneratedArtifacts +**/*.Server/ModelManifest.xml +_Pvt_Extensions + +# Paket dependency manager +.paket/paket.exe +paket-files/ + +# FAKE - F# Make +.fake/ + +# CodeRush personal settings +.cr/personal + +# Python Tools for Visual Studio (PTVS) +__pycache__/ +*.pyc + +# Cake - Uncomment if you are using it +# tools/** +# !tools/packages.config + +# Tabs Studio +*.tss + +# Telerik's JustMock configuration file +*.jmconfig + +# BizTalk build output +*.btp.cs +*.btm.cs +*.odx.cs +*.xsd.cs + +# OpenCover UI analysis results +OpenCover/ + +# Azure Stream Analytics local run output +ASALocalRun/ + +# MSBuild Binary and Structured Log +*.binlog + +# NVidia Nsight GPU debugger configuration file +*.nvuser + +# MFractors (Xamarin productivity tool) working folder +.mfractor/ + +# Local History for Visual Studio +.localhistory/ + +# Visual Studio History (VSHistory) files +.vshistory/ + +# BeatPulse healthcheck temp database +healthchecksdb + +# Backup folder for Package Reference Convert tool in Visual Studio 2017 +MigrationBackup/ + +# Ionide (cross platform F# VS Code tools) working folder +.ionide/ + +# Fody - auto-generated XML schema +FodyWeavers.xsd + +# VS Code files for those working on multiple tools +.vscode/ +.vscode/* +!.vscode/settings.json +!.vscode/tasks.json +!.vscode/launch.json +!.vscode/extensions.json +*.code-workspace + +# Local History for Visual Studio Code +.history/ + +# Windows Installer files from build outputs +*.cab +*.msi +*.msix +*.msm +*.msp + +# JetBrains Rider +*.sln.iml \ No newline at end of file diff --git a/readme.md b/readme.md new file mode 100644 index 0000000..d51ef58 --- /dev/null +++ b/readme.md @@ -0,0 +1,90 @@ +# DotnetStreams +Read text from STDIN regardless of the source. + +## Description +This library lets you read text input from STDIN that is entered from the console, piped to the application on the command line without any knowledge of the method. This is useful because you would normally not know if the stream has ended or not and have to check for it differently depending on the source. + +## Consuming the Library + +You can use the library in several ways: +- By copying the code to your source repo and adding a project reference to the DotnetStreams project. +- By adding a NuGet folder resource to your NuGet sources configuration which points to this project. +- By adding a NuGet reference to the DotnetStreams project in the repo at nuget.pillidar.com. + +> **How To Configure NuGet Sources** +> +> In Visual Studio 2022, right-click the `Dependencies` node in the Solution Explorer for your project. Click `Manage NuGet Packages`. In the upper-right corner, click the cog icon next to the `Package Source` dropdown. + +### Adding a NuGet Folder Resource + +Add a new Package Source. +| | | +| --- | --- | +| Name | DotnetStreams Folder | +| Source | C:\dev\DotnetStreams\source\DotnetStreams\bin\Release | + +### Adding a NuGet Repo Reference to nuget.pillidar.com + + +Add a new Package Source. +| | | +| --- | --- | +| Name | pillidar.com | +| Source | https://nuget.pillidar.com/v3/index.json | + +### Adding a NuGet repo at nuget.pillidar.com + + +## Usage Instructions + +### Consuming Application + +Your console app can use DotnetStreams to enable usage such as these: + +```powershell +echo "This is a test." | myconsoleapp.exe +``` + +```powershell +type myfile.txt | myconsoleapp.exe +``` + +```powershell +c:> myconsoleapp.exe +line 1 +line 2 + +line 3 +^Z +``` + +### Code Usage + +```powershell +static void Main(string[] args) +{ + ITextSource textSource; + IOutputTarget textTarget = new ConsoleOutputTarget(); + + if (args.Length > 0) + textSource = new FileTextSource(args[0]); + else + textSource = new StdInTextSource(); + + Execute( + textSource, + textTarget); +} + +public static void Execute(ITextSource source, IOutputTarget target) +{ + source.Open(); + target.Open(); + + foreach (string line in source.ReadAll()) + target.Output(line); + + target.Close(); + source.Close(); +} +``` diff --git a/source/DotnetStreams.sln b/source/DotnetStreams.sln new file mode 100644 index 0000000..a6e35f6 --- /dev/null +++ b/source/DotnetStreams.sln @@ -0,0 +1,37 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 17 +VisualStudioVersion = 17.13.35919.96 d17.13 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DotnetStreams", "DotnetStreams\DotnetStreams.csproj", "{42612FD1-4024-4091-B62F-3A897A4BBEF2}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DotnetStreamsTests", "DotnetStreamsTests\DotnetStreamsTests.csproj", "{1CE38FCB-E08F-8213-356A-F21626719E30}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DotnetStreamsApp", "DotnetStreamsApp\DotnetStreamsApp.csproj", "{7EF73074-AAA6-13D4-5EF8-6D91B220C690}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {42612FD1-4024-4091-B62F-3A897A4BBEF2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {42612FD1-4024-4091-B62F-3A897A4BBEF2}.Debug|Any CPU.Build.0 = Debug|Any CPU + {42612FD1-4024-4091-B62F-3A897A4BBEF2}.Release|Any CPU.ActiveCfg = Release|Any CPU + {42612FD1-4024-4091-B62F-3A897A4BBEF2}.Release|Any CPU.Build.0 = Release|Any CPU + {1CE38FCB-E08F-8213-356A-F21626719E30}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {1CE38FCB-E08F-8213-356A-F21626719E30}.Debug|Any CPU.Build.0 = Debug|Any CPU + {1CE38FCB-E08F-8213-356A-F21626719E30}.Release|Any CPU.ActiveCfg = Release|Any CPU + {1CE38FCB-E08F-8213-356A-F21626719E30}.Release|Any CPU.Build.0 = Release|Any CPU + {7EF73074-AAA6-13D4-5EF8-6D91B220C690}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {7EF73074-AAA6-13D4-5EF8-6D91B220C690}.Debug|Any CPU.Build.0 = Debug|Any CPU + {7EF73074-AAA6-13D4-5EF8-6D91B220C690}.Release|Any CPU.ActiveCfg = Release|Any CPU + {7EF73074-AAA6-13D4-5EF8-6D91B220C690}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {56B0A117-876A-43B1-9E7E-3966279BC007} + EndGlobalSection +EndGlobal diff --git a/source/DotnetStreams/AnonOutputTarget.cs b/source/DotnetStreams/AnonOutputTarget.cs new file mode 100644 index 0000000..0beef35 --- /dev/null +++ b/source/DotnetStreams/AnonOutputTarget.cs @@ -0,0 +1,30 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace DotnetStreams +{ + public class AnonOutputTarget : IOutputTarget + { + private readonly Action outputProc; + public AnonOutputTarget(Action outputProc) + { + this.outputProc = outputProc; + } + + public virtual void Close() + { + } + + public virtual void Open() + { + } + + public virtual void Output(string line) + { + this.outputProc?.Invoke(line); + } + } +} diff --git a/source/DotnetStreams/BinaryStdinReader.cs b/source/DotnetStreams/BinaryStdinReader.cs new file mode 100644 index 0000000..ab5ef9b --- /dev/null +++ b/source/DotnetStreams/BinaryStdinReader.cs @@ -0,0 +1,58 @@ +using System; + +namespace DotnetStreams +{ + public class BytesReadEventArgs + { + public byte[] Data { get; } + public int Size { get; } + public BytesReadEventArgs(byte[] data, int size) + { + this.Data = data; + this.Size = size; + } + } + + public delegate void BytesReadEventHandler(object sender, BytesReadEventArgs e); + + public class BinaryStdinReader + { + protected readonly Action dataReceiverProc; + protected readonly Action doneProc; + public event BytesReadEventHandler OnBytesRead; + public event EventHandler OnDone; + public BinaryStdinReader(Action dataReceiverProc, Action doneProc) + { + this.dataReceiverProc = dataReceiverProc; + this.doneProc = doneProc; + } + + public BinaryStdinReader() + { + } + + public void ReadBytes(Action receiverProc, Action doneProc) + { + using System.IO.Stream stdinStream = System.Console.OpenStandardInput(); + + int totalBytesRead = 0; + int bufferSize = 2048; + byte[] buffer = new byte[bufferSize]; + int bytesRead = stdinStream.Read(buffer, 0, bufferSize); + while (bytesRead > 0) + { + OnBytesRead?.Invoke(this, new BytesReadEventArgs(buffer, bytesRead)); + receiverProc?.Invoke(buffer, bytesRead); + + if (bytesRead < bufferSize) + break; + + bytesRead = stdinStream.Read(buffer, 0, bufferSize); + totalBytesRead += bytesRead; + } + + OnDone?.Invoke(this, new EventArgs()); + doneProc?.Invoke(totalBytesRead); + } + } +} diff --git a/source/DotnetStreams/ConsoleOutputTarget.cs b/source/DotnetStreams/ConsoleOutputTarget.cs new file mode 100644 index 0000000..8108668 --- /dev/null +++ b/source/DotnetStreams/ConsoleOutputTarget.cs @@ -0,0 +1,22 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace DotnetStreams +{ + public class ConsoleOutputTarget : IOutputTarget + { + public virtual void Open() + { + } + public virtual void Output(string line) + { + Console.WriteLine(line); + } + public virtual void Close() + { + } + } +} diff --git a/source/DotnetStreams/DotnetStreams.csproj b/source/DotnetStreams/DotnetStreams.csproj new file mode 100644 index 0000000..5648e5c --- /dev/null +++ b/source/DotnetStreams/DotnetStreams.csproj @@ -0,0 +1,16 @@ + + + + net5.0 + enable + true + Phil Gilmore + Classes to seamlessly abstract StdIn, StdOut, coded lists or file streams in your console applications. + + MIT + true + true + snupkg + + + diff --git a/source/DotnetStreams/FileTextSource.cs b/source/DotnetStreams/FileTextSource.cs new file mode 100644 index 0000000..7633ef7 --- /dev/null +++ b/source/DotnetStreams/FileTextSource.cs @@ -0,0 +1,71 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.IO; + +namespace DotnetStreams +{ + public class FileTextSource : ITextSource + { + protected FileStream? file; + protected StreamReader? reader; + protected string filename; + + public FileTextSource(string filename) + { + this.filename = filename; + file = null; + reader = null; + } + + public virtual void Open() + { + file = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.Read); + reader = new StreamReader(file); + } + + public virtual IEnumerable ReadAll() + { + string? line = reader?.ReadLine(); + while (line != null) + { + yield return line; + line = reader?.ReadLine(); + } + } + + public virtual string Read() + { + if (!Eof()) + return reader?.ReadLine() ?? string.Empty; + else + return string.Empty; + } + + public virtual bool Eof() + { + return reader?.EndOfStream ?? true; + } + + public virtual void Close() + { + try + { + file?.Flush(); + } + finally + { + try + { + file?.Close(); + } + finally + { + file?.Dispose(); + } + } + } + } +} diff --git a/source/DotnetStreams/IOutputTarget.cs b/source/DotnetStreams/IOutputTarget.cs new file mode 100644 index 0000000..1a83e4b --- /dev/null +++ b/source/DotnetStreams/IOutputTarget.cs @@ -0,0 +1,15 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace DotnetStreams +{ + public interface IOutputTarget + { + void Open(); + void Output(string line); + void Close(); + } +} diff --git a/source/DotnetStreams/ITextSource.cs b/source/DotnetStreams/ITextSource.cs new file mode 100644 index 0000000..aab3daa --- /dev/null +++ b/source/DotnetStreams/ITextSource.cs @@ -0,0 +1,17 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace DotnetStreams +{ + public interface ITextSource + { + void Open(); + IEnumerable ReadAll(); + string Read(); + bool Eof(); + void Close(); + } +} diff --git a/source/DotnetStreams/ListOutputTarget.cs b/source/DotnetStreams/ListOutputTarget.cs new file mode 100644 index 0000000..f38700b --- /dev/null +++ b/source/DotnetStreams/ListOutputTarget.cs @@ -0,0 +1,30 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace DotnetStreams +{ + public class ListOutputTarget : IOutputTarget + { + public IList OutputList { get; } + public ListOutputTarget(IList outputList) + { + this.OutputList = outputList; + } + + public virtual void Open() + { + } + + public virtual void Output(string text) + { + OutputList.Add(text); + } + + public virtual void Close() + { + } + } +} diff --git a/source/DotnetStreams/ListTextSource.cs b/source/DotnetStreams/ListTextSource.cs new file mode 100644 index 0000000..026e307 --- /dev/null +++ b/source/DotnetStreams/ListTextSource.cs @@ -0,0 +1,71 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace DotnetStreams +{ + public class ListTextSource : ITextSource + { + private bool isEof; + private readonly IEnumerable source; + private IEnumerator? enumerator; + //private string lastValue; + private bool firstIsRead; + private string nextLine; + public ListTextSource(IEnumerable source) + { + this.source = source; + enumerator = null; + firstIsRead = false; + nextLine = string.Empty; + } + + public virtual void Open() + { + } + + public virtual IEnumerable ReadAll() + { + return source.AsEnumerable(); + } + + public virtual string Read() + { + if (enumerator == null) + enumerator = source.GetEnumerator(); + + string thisLine; + if (!firstIsRead) + { + // Read the first, put it in the "last" buffer. + isEof = !enumerator.MoveNext(); + nextLine = enumerator.Current; + firstIsRead = true; + } + + thisLine = nextLine; + + if (!isEof) + { + isEof = !enumerator.MoveNext(); + if (!isEof) + nextLine = enumerator.Current; + else + nextLine = string.Empty; + + } + + return thisLine; + } + + public virtual bool Eof() => isEof; + + public virtual void Close() + { + enumerator = null; + isEof = false; + } + } +} diff --git a/source/DotnetStreams/ProcessedConsoleOutputTarget.cs b/source/DotnetStreams/ProcessedConsoleOutputTarget.cs new file mode 100644 index 0000000..c462011 --- /dev/null +++ b/source/DotnetStreams/ProcessedConsoleOutputTarget.cs @@ -0,0 +1,26 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace DotnetStreams +{ + public class ProcessedConsoleOutputTarget : ConsoleOutputTarget + { + protected Func processorFunc; + public ProcessedConsoleOutputTarget(Func processorFunc) : base() + { + if (processorFunc != null) + this.processorFunc = processorFunc; + else + this.processorFunc = line => line; + } + + public override void Output(string line) + { + string output = processorFunc?.Invoke(line) ?? string.Empty; + Console.WriteLine(output); + } + } +} diff --git a/source/DotnetStreams/StdInTextSource.cs b/source/DotnetStreams/StdInTextSource.cs new file mode 100644 index 0000000..543755e --- /dev/null +++ b/source/DotnetStreams/StdInTextSource.cs @@ -0,0 +1,47 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace DotnetStreams +{ + public class StdInTextSource : ITextSource + { + protected bool isEof; + + public virtual void Open() + { + isEof = false; + } + + public virtual IEnumerable ReadAll() + { + string? s = Console.ReadLine(); + while (s != null) + { + yield return s; + s = Console.ReadLine(); + } + isEof = true; + } + + public virtual string Read() + { + string? s = Console.ReadLine(); + if (s == null) + { + isEof = true; + return string.Empty; + } + else + return s; + } + + public virtual bool Eof() => isEof; + + public virtual void Close() + { + } + } +} diff --git a/source/DotnetStreamsApp/DotnetStreams.cs b/source/DotnetStreamsApp/DotnetStreams.cs new file mode 100644 index 0000000..5f76fa7 --- /dev/null +++ b/source/DotnetStreamsApp/DotnetStreams.cs @@ -0,0 +1,297 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace DotnetStreams +{ + //public interface ITextSource + //{ + // void Open(); + // IEnumerable ReadAll(); + // string Read(); + // bool Eof(); + // void Close(); + //} + + //public class StdInTextSource : ITextSource + //{ + // protected bool isEof; + + // public virtual void Open() + // { + // isEof = false; + // } + + // public virtual IEnumerable ReadAll() + // { + // string? s = Console.ReadLine(); + // while (s != null) + // { + // yield return s; + // s = Console.ReadLine(); + // } + // isEof = true; + // } + + // public virtual string Read() + // { + // string? s = Console.ReadLine(); + // if (s == null) + // { + // isEof = true; + // return string.Empty; + // } + // else + // return s; + // } + + // public virtual bool Eof() => isEof; + + // public virtual void Close() + // { + // } + //} + + //public class FileTextSource : ITextSource + //{ + // protected FileStream? file; + // protected StreamReader? reader; + // protected string filename; + + // public FileTextSource(string filename) + // { + // this.filename = filename; + // file = null; + // reader = null; + // } + + // public virtual void Open() + // { + // file = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.Read); + // reader = new StreamReader(file); + // } + + // public virtual IEnumerable ReadAll() + // { + // string? line = reader?.ReadLine(); + // while (line != null) + // { + // yield return line; + // line = reader?.ReadLine(); + // } + // } + + // public virtual string Read() + // { + // if (!Eof()) + // return reader?.ReadLine() ?? string.Empty; + // else + // return string.Empty; + // } + + // public virtual bool Eof() + // { + // return reader?.EndOfStream ?? true; + // } + + // public virtual void Close() + // { + // try + // { + // file?.Flush(); + // } + // finally + // { + // try + // { + // file?.Close(); + // } + // finally + // { + // file?.Dispose(); + // } + // } + // } + //} + + //public class ListTextSource : ITextSource + //{ + // private bool isEof; + // private readonly IEnumerable source; + // private IEnumerator? enumerator; + // //private string lastValue; + // private bool firstIsRead; + // private string nextLine; + // public ListTextSource(IEnumerable source) + // { + // this.source = source; + // enumerator = null; + // firstIsRead = false; + // nextLine = string.Empty; + // } + + // public virtual void Open() + // { + // } + + // public virtual IEnumerable ReadAll() + // { + // return source.AsEnumerable(); + // } + + // public virtual string Read() + // { + // if (enumerator == null) + // enumerator = source.GetEnumerator(); + + // string thisLine; + // if (!firstIsRead) + // { + // // Read the first, put it in the "last" buffer. + // isEof = !enumerator.MoveNext(); + // nextLine = enumerator.Current; + // firstIsRead = true; + // } + + // thisLine = nextLine; + + // if (!isEof) + // { + // isEof = !enumerator.MoveNext(); + // if (!isEof) + // nextLine = enumerator.Current; + // else + // nextLine = string.Empty; + + // } + + // return thisLine; + // } + + // public virtual bool Eof() => isEof; + + // public virtual void Close() + // { + // enumerator = null; + // isEof = false; + // } + //} + + //public interface IOutputTarget + //{ + // void Open(); + // void Output(string line); + // void Close(); + //} + + //public class ConsoleOutputTarget : IOutputTarget + //{ + // public virtual void Open() + // { + // } + // public virtual void Output(string line) + // { + // Console.WriteLine(line); + // } + // public virtual void Close() + // { + // } + //} + + //public class ProcessedConsoleOutputTarget : ConsoleOutputTarget + //{ + // protected Func processorFunc; + // public ProcessedConsoleOutputTarget(Func processorFunc) : base() + // { + // if (processorFunc != null) + // this.processorFunc = processorFunc; + // else + // this.processorFunc = line => line; + // } + + // public override void Output(string line) + // { + // string output = processorFunc?.Invoke(line) ?? string.Empty; + // Console.WriteLine(output); + // } + //} + + //public class ListOutputTarget : IOutputTarget + //{ + // public IList OutputList { get; } + // public ListOutputTarget(IList outputList) + // { + // this.OutputList = outputList; + // } + + // public virtual void Open() + // { + // } + + // public virtual void Output(string text) + // { + // OutputList.Add(text); + // } + + // public virtual void Close() + // { + // } + //} + + //public class BytesReadEventArgs + //{ + // public byte[] Data { get; } + // public int Size { get; } + // public BytesReadEventArgs(byte[] data, int size) + // { + // this.Data = data; + // this.Size = size; + // } + //} + + //public delegate void BytesReadEventHandler(object sender, BytesReadEventArgs e); + + //public class BinaryStdinReader + //{ + // protected readonly Action dataReceiverProc; + // protected readonly Action doneProc; + // public event BytesReadEventHandler OnBytesRead; + // public event EventHandler OnDone; + // public BinaryStdinReader(Action dataReceiverProc, Action doneProc) + // { + // this.dataReceiverProc = dataReceiverProc; + // this.doneProc = doneProc; + // } + + // public BinaryStdinReader() + // { + // } + + // public void ReadBytes(Action receiverProc, Action doneProc) + // { + // using System.IO.Stream stdinStream = System.Console.OpenStandardInput(); + + // int totalBytesRead = 0; + // int bufferSize = 2048; + // byte[] buffer = new byte[bufferSize]; + // int bytesRead = stdinStream.Read(buffer, 0, bufferSize); + // while (bytesRead > 0) + // { + // OnBytesRead?.Invoke(this, new BytesReadEventArgs(buffer, bytesRead)); + // receiverProc?.Invoke(buffer, bytesRead); + + // if (bytesRead < bufferSize) + // break; + + // bytesRead = stdinStream.Read(buffer, 0, bufferSize); + // totalBytesRead += bytesRead; + // } + + // OnDone?.Invoke(this, new EventArgs()); + // doneProc?.Invoke(totalBytesRead); + // } + //} +} diff --git a/source/DotnetStreamsApp/DotnetStreamsApp.csproj b/source/DotnetStreamsApp/DotnetStreamsApp.csproj new file mode 100644 index 0000000..be9b27e --- /dev/null +++ b/source/DotnetStreamsApp/DotnetStreamsApp.csproj @@ -0,0 +1,14 @@ + + + + Exe + net5.0 + enable + nullable + + + + + + + diff --git a/source/DotnetStreamsApp/Program.cs b/source/DotnetStreamsApp/Program.cs new file mode 100644 index 0000000..a60607d --- /dev/null +++ b/source/DotnetStreamsApp/Program.cs @@ -0,0 +1,87 @@ +using System; +using System.IO; +using System.Linq; +using DotnetStreams; + +namespace StreamsTest +{ + class Program + { + + static void Main(string[] args) + { + //Program p = new(); + + ITextSource textSource; + IOutputTarget textTarget = new ConsoleOutputTarget(); + + if (args.Length > 0) + textSource = new FileTextSource(args[0]); + else + textSource = new StdInTextSource(); + + + Execute( + textSource, + textTarget); + } + + // Works, but needs to be more compact. + //static void Main(string[] args) + //{ + // Program p = new Program(); + + // ITextSource textSource = null; + + // if (args.Length > 0) + // { + // var filename = args[0]; + // if (!File.Exists(filename)) + // { + // Console.WriteLine($"File not found ({filename})."); + // Environment.Exit(1); + // } + // else + // textSource = new FileTextSource(filename); + // } + // else + // textSource = new StdInTextSource(); + + // p.Execute( + // textSource, + // new ConsoleOutputTarget()); + //} + + + //public void ExecuteReadLine(string[] args) + //{ + // string s = Console.ReadLine(); + // // This terminates on blank lines, no surprise + // //while (!string.IsNullOrEmpty(s)) + // while (s != null) + // { + // s = s.Replace("\r", "{CR}") + // .Replace("\n", "{LF}") + // .Replace("\t", "{TAB}"); + // if (s == string.Empty) + // s = "{EMPTYSTRING}"; + // Console.WriteLine($"{s}"); + // s = Console.ReadLine(); + // } + // if (s == null) + // Console.WriteLine("/s/ is null"); + //} + + public static void Execute(ITextSource source, IOutputTarget target) + { + source.Open(); + target.Open(); + + foreach (string line in source.ReadAll()) + target.Output(line); + + target.Close(); + source.Close(); + } + } +} diff --git a/source/DotnetStreamsApp/Properties/launchSettings.json b/source/DotnetStreamsApp/Properties/launchSettings.json new file mode 100644 index 0000000..f7e67bc --- /dev/null +++ b/source/DotnetStreamsApp/Properties/launchSettings.json @@ -0,0 +1,9 @@ +{ + "profiles": { + "StreamsTest": { + "commandName": "Project", + "commandLineArgs": "C:\\Users\\Phil\\source\\repos\\DotnetStreams\\DotnetStreamsApp\\delme.txt", + "sqlDebugging": true + } + } +} \ No newline at end of file diff --git a/source/DotnetStreamsApp/delme.txt b/source/DotnetStreamsApp/delme.txt new file mode 100644 index 0000000..6afc597 --- /dev/null +++ b/source/DotnetStreamsApp/delme.txt @@ -0,0 +1,4 @@ +Line 1 +Line 2 + +Line 3 \ No newline at end of file diff --git a/source/DotnetStreamsTests/ConsoleOutputTargetTests.cs b/source/DotnetStreamsTests/ConsoleOutputTargetTests.cs new file mode 100644 index 0000000..8016cff --- /dev/null +++ b/source/DotnetStreamsTests/ConsoleOutputTargetTests.cs @@ -0,0 +1,38 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Xunit; +using Shouldly; +using DotnetStreams; +using System.IO; +using DotnetStreamsTests.Testables; + +namespace DotnetStreamsTests +{ + public class ConsoleOutputTargetTests + { + private IOutputTarget outputTarget; + + [Fact] + public void WritesToOutputStream() + { + ListWriter writer = new(); + outputTarget = new TestableConsoleOutputTarget(writer); + + outputTarget.Open(); + outputTarget.Output("1"); + outputTarget.Output("2"); + outputTarget.Output(""); + outputTarget.Output("3"); + outputTarget.Close(); + + writer.Lines.Count.ShouldBe(4); + writer.Lines[0].ShouldBe("1"); + writer.Lines[1].ShouldBe("2"); + writer.Lines[2].ShouldBe(string.Empty); + writer.Lines[3].ShouldBe("3"); + } + } +} diff --git a/source/DotnetStreamsTests/DotnetStreamsTests.csproj b/source/DotnetStreamsTests/DotnetStreamsTests.csproj new file mode 100644 index 0000000..f44f485 --- /dev/null +++ b/source/DotnetStreamsTests/DotnetStreamsTests.csproj @@ -0,0 +1,27 @@ + + + + net5.0 + + false + + + + + + + + runtime; build; native; contentfiles; analyzers; buildtransitive + all + + + runtime; build; native; contentfiles; analyzers; buildtransitive + all + + + + + + + + diff --git a/source/DotnetStreamsTests/ListOutputTargetTests.cs b/source/DotnetStreamsTests/ListOutputTargetTests.cs new file mode 100644 index 0000000..bec3d9e --- /dev/null +++ b/source/DotnetStreamsTests/ListOutputTargetTests.cs @@ -0,0 +1,27 @@ +using DotnetStreams; +using System; +using System.Collections.Generic; +using Xunit; +using Shouldly; + +namespace DotnetStreamsTests +{ + public class ListOutputTargetTests + { + [Fact] + public void WritesToList() + { + ListOutputTarget target = new(new List()); + target.Output("1"); + target.Output("2"); + target.Output(""); + target.Output("3"); + + target.OutputList.Count.ShouldBe(4); + target.OutputList[0].ShouldBe("1"); + target.OutputList[1].ShouldBe("2"); + target.OutputList[2].ShouldBe(string.Empty); + target.OutputList[3].ShouldBe("3"); + } + } +} diff --git a/source/DotnetStreamsTests/ListTextSourceTests.cs b/source/DotnetStreamsTests/ListTextSourceTests.cs new file mode 100644 index 0000000..fb24e42 --- /dev/null +++ b/source/DotnetStreamsTests/ListTextSourceTests.cs @@ -0,0 +1,39 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Xunit; +using Shouldly; +using DotnetStreams; + +namespace DotnetStreamsTests +{ + public class ListTextSourceTests + { + [Fact] + public void ReadsFromList() + { + ITextSource reader = new ListTextSource(new[] { "1", "2", "", "3" }); + string s0 = reader.Read(); + s0.ShouldNotBeNull(); + s0.ShouldBe("1"); + reader.Eof().ShouldBe(false); + + string s1 = reader.Read(); + s1.ShouldNotBeNull(); + s1.ShouldBe("2"); + reader.Eof().ShouldBe(false); + + string s2 = reader.Read(); + s2.ShouldNotBeNull(); + s2.ShouldBe(string.Empty); + reader.Eof().ShouldBe(false); + + string s3 = reader.Read(); + s3.ShouldNotBeNull(); + s3.ShouldBe("3"); + reader.Eof().ShouldBe(true); + } + } +} diff --git a/source/DotnetStreamsTests/StdInTextSourceTests.cs b/source/DotnetStreamsTests/StdInTextSourceTests.cs new file mode 100644 index 0000000..ab54acb --- /dev/null +++ b/source/DotnetStreamsTests/StdInTextSourceTests.cs @@ -0,0 +1,210 @@ +using DotnetStreamsTests.Testables; +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Xunit; +using Shouldly; +using DotnetStreams; + +namespace DotnetStreamsTests +{ + public class StdInTextSourceTests + { + private static TextReader CreateStdIn() + { + return new ListTextReader(new[] { "1", "2", "", "3" }); + } + + private static void WrapStdInTest(Action testCode) + { + var oldInputReader = System.Console.In; + try + { + TextReader reader = CreateStdIn(); + System.Console.SetIn(reader); + + ITextSource stdin = new StdInTextSource(); + stdin.Open(); + try + { + testCode?.Invoke(stdin); + } + finally + { + stdin.Close(); + } + } + finally + { + System.Console.SetIn(oldInputReader); + } + } + + [Fact] + public void CanReadAllFromStandardIn() + { + WrapStdInTest(stdin => + { + var actual = stdin.ReadAll().ToList(); + actual.Count.ShouldBe(4); + actual[0].ShouldBe("1"); + actual[1].ShouldBe("2"); + actual[2].ShouldBe(string.Empty); + actual[3].ShouldBe("3"); + }); + } + + //{ + + // // Fake the StdIn + // var oldInputReader = System.Console.In; + // try + // { + // TextReader reader = CreateStdIn(); + // System.Console.SetIn(reader); + + // ITextSource stdin = new StdInTextSource(); + // stdin.Open(); + // try + // { + // var actual = stdin.ReadAll().ToList(); + // actual.Count.ShouldBe(4); + // actual[0].ShouldBe("1"); + // actual[1].ShouldBe("2"); + // actual[2].ShouldBe(string.Empty); + // actual[3].ShouldBe("3"); + // } + // finally + // { + // stdin.Close(); + // } + // } + // finally + // { + // System.Console.SetIn(oldInputReader); + // } + //} + + [Fact] + public void CanReadIndividualLinesFromStandardIn() + { + WrapStdInTest(stdin => + { + string s; + s = stdin.Read(); + stdin.Eof().ShouldBe(false); + s.ShouldBe("1"); + + s = stdin.Read(); + stdin.Eof().ShouldBe(false); + s.ShouldBe("2"); + + s = stdin.Read(); + stdin.Eof().ShouldBe(false); + s.ShouldBe(string.Empty); + + s = stdin.Read(); + stdin.Eof().ShouldBe(false); + s.ShouldBe("3"); + + s = stdin.Read(); + stdin.Eof().ShouldBe(true); + }); + + //// Fake the StdIn + //var oldInputReader = System.Console.In; + //try + //{ + // TextReader reader = CreateStdIn(); + // System.Console.SetIn(reader); + + // ITextSource stdin = new StdInTextSource(); + // stdin.Open(); + // try + // { + // string s; + // s = stdin.Read(); + // stdin.Eof().ShouldBe(false); + // s.ShouldBe("1"); + + // s = stdin.Read(); + // stdin.Eof().ShouldBe(false); + // s.ShouldBe("2"); + + // s = stdin.Read(); + // stdin.Eof().ShouldBe(false); + // s.ShouldBe(string.Empty); + + // s = stdin.Read(); + // stdin.Eof().ShouldBe(false); + // s.ShouldBe("3"); + + // s = stdin.Read(); + // stdin.Eof().ShouldBe(true); + // } + // finally + // { + // stdin.Close(); + // } + //} + //finally + //{ + // System.Console.SetIn(oldInputReader); + //} + } + + [Fact] + public void CanWhileLoopThroughStdInProperly() + { + WrapStdInTest(stdin => + { + int lineCount = 0; + var s = stdin.Read(); + while (!stdin.Eof()) + { + lineCount++; + s = stdin.Read(); + } + + lineCount.ShouldBe(4); + }); + } + + //{ + // // Fake the StdIn + // var oldInputReader = System.Console.In; + // try + // { + // TextReader reader = CreateStdIn(); + // System.Console.SetIn(reader); + + // ITextSource stdin = new StdInTextSource(); + // stdin.Open(); + // try + // { + // int lineCount = 0; + // var s = stdin.Read(); + // while (!stdin.Eof()) + // { + // // Do stuff with s here normally. + // lineCount++; + // s = stdin.Read(); + // } + + // lineCount.ShouldBe(4); + // } + // finally + // { + // stdin.Close(); + // } + // } + // finally + // { + // System.Console.SetIn(oldInputReader); + // } + //} + } +} diff --git a/source/DotnetStreamsTests/Testables/ListTextReader.cs b/source/DotnetStreamsTests/Testables/ListTextReader.cs new file mode 100644 index 0000000..829256c --- /dev/null +++ b/source/DotnetStreamsTests/Testables/ListTextReader.cs @@ -0,0 +1,26 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace DotnetStreamsTests.Testables +{ + public class ListTextReader : TextReader + { + private readonly IEnumerator enumerator; + public ListTextReader(IEnumerable data) + { + enumerator = data.GetEnumerator(); + } + + public override string ReadLine() + { + if (enumerator.MoveNext()) + return enumerator.Current; + else + return null; + } + } +} diff --git a/source/DotnetStreamsTests/Testables/ListWriter.cs b/source/DotnetStreamsTests/Testables/ListWriter.cs new file mode 100644 index 0000000..14cad3c --- /dev/null +++ b/source/DotnetStreamsTests/Testables/ListWriter.cs @@ -0,0 +1,30 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace DotnetStreamsTests.Testables +{ + public class ListWriter : TextWriter + { + public List Lines { get; } + public override Encoding Encoding => Encoding.UTF8; + + public ListWriter() + { + Lines = new(); + } + + public override void Write(string value) + { + Lines.Add(value); + } + + public override void WriteLine(string value) + { + Lines.Add(value); + } + } +} diff --git a/source/DotnetStreamsTests/Testables/TestableConsoleOutputTarget.cs b/source/DotnetStreamsTests/Testables/TestableConsoleOutputTarget.cs new file mode 100644 index 0000000..df3fb3c --- /dev/null +++ b/source/DotnetStreamsTests/Testables/TestableConsoleOutputTarget.cs @@ -0,0 +1,24 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Text; +using DotnetStreams; + +namespace DotnetStreamsTests.Testables +{ + public class TestableConsoleOutputTarget : ConsoleOutputTarget, IDisposable + { + private readonly TextWriter previousOutWriter; + public TestableConsoleOutputTarget(TextWriter outWriter) : base() + { + previousOutWriter = System.Console.Out; + System.Console.SetOut(outWriter); + } + + public void Dispose() + { + + System.Console.SetOut(previousOutWriter); + } + } +}