Skip to content

Commit

Permalink
优化编码至 stdout 的代码
Browse files Browse the repository at this point in the history
  • Loading branch information
lc6464 committed Dec 12, 2023
1 parent a146eca commit 1db48e4
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 35 deletions.
3 changes: 2 additions & 1 deletion Base16384.Net.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,14 @@
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<Version>1.1.0.0</Version>
<Version>2.0.0.0</Version>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="LC6464.Base16384" Version="2.1.0" />
</ItemGroup>
<ItemGroup>
<Using Include="System.Runtime.InteropServices" />
<Using Include="LC6464.Base16384" />
<Using Include="ConsoleHelpers" />
</ItemGroup>
</Project>
19 changes: 19 additions & 0 deletions Helpers.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
namespace ConsoleHelpers;

public static class Helpers {
public static int WriteToStdOut<T>(Func<T, Stream, long> func, T input, Stream? stdout = null) {
try {
stdout ??= Console.OpenStandardOutput();
try {
func(input, stdout);
} catch {
return 4;
} finally {
stdout.Dispose();
}
} catch {
return 3;
}
return 0;
}
}
50 changes: 16 additions & 34 deletions Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -20,28 +20,20 @@ 4. 编解码失败
using var stdin = Console.OpenStandardInput();
if (args.Length == 2 || args[2] == "-") {
// Write to stdout
try {
using var stdout = Console.OpenStandardOutput();
try {
Base16384.EncodeToStream(stdin, stdout);
} catch {
return 4;
}
} catch {
return 3;
}
} else {
// Write to file
FileInfo info = new(args[2]);
Console.Write($"<stdin> -> {info.Name} ... ");
try {
Base16384.EncodeToNewFile(stdin, info);
} catch {
Console.WriteLine("Failed.");
return 4;
}
Console.WriteLine("Done.");
return Helpers.WriteToStdOut(Base16384.EncodeToStream, stdin);
}

// Write to file
FileInfo info = new(args[2]);
Console.Write($"<stdin> -> {info.Name} ... ");
try {
Base16384.EncodeToNewFile(stdin, info);
} catch {
Console.WriteLine("Failed.");
return 4;
}
Console.WriteLine("Done.");

} catch {
if (args.Length != 2 && args[2] != "-") {
Console.WriteLine("Can not open stdin.");
Expand All @@ -52,19 +44,9 @@ 4. 编解码失败
// Read from file
if (args is [.., "-"]) {
// Write to stdout
if (!File.Exists(args[1])) {
return 2;
}
try {
using var stdout = Console.OpenStandardOutput();
try {
Base16384.EncodeFromFileToStream(new(args[1]), stdout);
} catch {
return 4;
}
} catch {
return 3;
}
return !File.Exists(args[1])
? 2
: Helpers.WriteToStdOut(Base16384.EncodeFromFileToStream, new FileInfo(args[1]));
} else if (args.Length == 2) {
// Write to .decoded file
if (!File.Exists(args[1])) {
Expand Down

0 comments on commit 1db48e4

Please sign in to comment.