-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.source.code.cs
More file actions
185 lines (154 loc) · 5.2 KB
/
Program.source.code.cs
File metadata and controls
185 lines (154 loc) · 5.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
using K4os.Compression.LZ4;
using SharpCompress.Common;
using SharpCompress.Writers;
using SharpCompress.Writers.Zip;
using System.Collections.Concurrent;
using System.IO.Compression;
using System.Text;
using System.Threading.Tasks;
class Program
{
static int processedFiles = 0;
static int totalFiles = 0;
static object progressLock = new object();
static void Main(string[] args)
{
if (args.Length == 1 && (args[0] == "-h" || args[0] == "--help"))
{
PrintHelp();
return;
}
if (args.Length == 0)
{
Console.WriteLine("Usage: ripzip <file_or_folder>");
Console.WriteLine("Use ripzip -h for help.");
return;
}
string input = args[0];
if (!File.Exists(input) && !Directory.Exists(input))
{
Console.WriteLine("Error: file or folder not found.");
return;
}
string output = input.TrimEnd(Path.DirectorySeparatorChar) + ".zip";
var sw = System.Diagnostics.Stopwatch.StartNew();
List<string> files = new();
string baseDir = null;
if (File.Exists(input))
{
files.Add(input);
}
else
{
baseDir = Path.GetFullPath(input);
files.AddRange(Directory.GetFiles(baseDir, "*", SearchOption.AllDirectories));
}
totalFiles = files.Count;
using var fs = File.Create(output);
var options = new ZipWriterOptions(CompressionType.None);
using var writer = new ZipWriter(fs, options);
var queue = new BlockingCollection<(string EntryName, byte[] Data)>(Environment.ProcessorCount * 4);
var writerTask = Task.Run(() =>
{
foreach (var item in queue.GetConsumingEnumerable())
{
using var ms = new MemoryStream(item.Data);
writer.Write(item.EntryName, ms);
}
});
Parallel.ForEach(
files,
new ParallelOptions { MaxDegreeOfParallelism = Environment.ProcessorCount },
file =>
{
try
{
string entryName = baseDir == null
? Path.GetFileName(file)
: Path.GetRelativePath(baseDir, file);
byte[] data = File.ReadAllBytes(file);
if (IsAlreadyCompressed(file))
{
queue.Add((entryName, data));
UpdateProgress();
return;
}
byte[] compressed = CompressSmart(data);
queue.Add((entryName, compressed));
UpdateProgress();
}
catch (Exception ex)
{
Console.WriteLine($"Error on '{file}': {ex.Message}");
}
});
queue.CompleteAdding();
writerTask.Wait();
sw.Stop();
Console.WriteLine($"\nCompleted in {sw.Elapsed.TotalSeconds:F2} seconds");
}
static void PrintHelp()
{
Console.WriteLine("ripzip");
Console.WriteLine();
Console.WriteLine("Usage:");
Console.WriteLine(" ripzip <file_or_folder> Compress");
Console.WriteLine(" ripzip -h Show this help");
}
static void UpdateProgress()
{
int done = Interlocked.Increment(ref processedFiles);
double percent = (double)done / totalFiles * 100.0;
int barWidth = 30;
int filled = (int)(percent / 100.0 * barWidth);
string bar = "[" + new string('#', filled) + new string('-', barWidth - filled) + "]";
lock (progressLock)
{
Console.CursorLeft = 0;
Console.Write($"{bar} {percent:0.0}% ({done}/{totalFiles})");
}
}
static bool IsAlreadyCompressed(string file)
{
string ext = Path.GetExtension(file).ToLower();
return ext switch
{
".png" or ".jpg" or ".jpeg" or ".mp4" or ".mp3" or ".zip" or ".rar" or ".7z" or ".pdf" or ".exe" or ".dll" => true,
_ => false
};
}
static byte[] CompressSmart(byte[] input)
{
if (input.Length < 64 * 1024)
return Deflate(input, CompressionLevel.Fastest);
if (LooksLikeText(input))
return Deflate(input, CompressionLevel.Optimal);
return LZ4Fast(input);
}
static bool LooksLikeText(byte[] data)
{
int count = Math.Min(2000, data.Length);
for (int i = 0; i < count; i++)
{
if (data[i] == 0) return false;
}
return true;
}
static byte[] LZ4Fast(byte[] input)
{
int max = LZ4Codec.MaximumOutputSize(input.Length);
byte[] output = new byte[max];
int encoded = LZ4Codec.Encode(input, 0, input.Length, output, 0, max);
Array.Resize(ref output, encoded);
return output;
}
static byte[] Deflate(byte[] input, CompressionLevel level)
{
using var ms = new MemoryStream();
using (var ds = new DeflateStream(ms, level))
{
ds.Write(input, 0, input.Length);
}
return ms.ToArray();
}
}