-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathScriptParser.cs
More file actions
279 lines (255 loc) · 11.5 KB
/
ScriptParser.cs
File metadata and controls
279 lines (255 loc) · 11.5 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
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
using System.Diagnostics;
using System.Globalization;
namespace FLAC_Benchmark_H
{
public static class ScriptParser
{
/// <summary>
/// Expands script lines like "-preset[fast,medium] -j[1..4]" into all possible parameter combinations.
/// Uses square brackets [ ] to avoid conflict with FLAC's { } syntax (e.g. --picture={...}).
/// Supports both explicit text values (e.g. [fast, medium, slow]) and numeric ranges (e.g. [1..4]).
/// Handles nested brackets correctly.
/// </summary>
/// <param name="input">Input script string</param>
/// <returns>List of expanded strings</returns>
public static List<string> ExpandScriptLine(string input)
{
// Base case: if there are no brackets, return the input as is
if (string.IsNullOrWhiteSpace(input) || !input.Contains('[') || !input.Contains(']'))
{
return [input];
}
// Check for balanced brackets
if (input.Count(c => c == '[') != input.Count(c => c == ']'))
{
Debug.WriteLine("Mismatched brackets in script: " + input);
return []; // Invalid syntax
}
// Find the innermost [...] block
int lastOpenIndex = -1;
int firstCloseIndex = -1;
for (int i = 0; i < input.Length; i++)
{
if (input[i] == '[')
{
lastOpenIndex = i;
}
else if (input[i] == ']')
{
firstCloseIndex = i;
break; // Found the first closing bracket after the last open
}
}
// If no valid pair found, return as is
if (lastOpenIndex == -1 || firstCloseIndex == -1 || lastOpenIndex > firstCloseIndex)
{
return [input];
}
// Extract parts: prefix, content, suffix
string prefix = input[..lastOpenIndex];
string content = input.Substring(lastOpenIndex + 1, firstCloseIndex - lastOpenIndex - 1);
string suffix = input[(firstCloseIndex + 1)..];
// Parse the innermost content
List<string> parsedValues = ParseRange(content);
List<string> result = [];
// For each possible value from the innermost range, recursively expand the full string
foreach (string value in parsedValues)
{
string newInput = prefix + value + suffix;
List<string> expanded = ExpandScriptLine(newInput); // Recursive call
result.AddRange(expanded);
}
// Remove duplicates and sort naturally
return [.. result.Distinct().OrderBy(x => x, new NaturalStringComparer())];
}
/// <summary>
/// Parses a range string like "fast, medium..slow, 4.5" into a list of strings.
/// Handles explicit values and numeric ranges.
/// Text values are processed as-is. Numeric ranges are expanded.
/// Empty values (e.g. from "[m,]") are treated as empty strings.
/// </summary>
/// <param name="content">Comma-separated values and ranges</param>
/// <returns>List of strings from parsed values/ranges</returns>
private static List<string> ParseRange(string content)
{
List<string> values = [];
// Split by comma and process each part
foreach (string part in content.Split(','))
{
string trimmed = part.Trim(); // Remove leading/trailing whitespace
if (trimmed.Contains(".."))
{
// --- Handle numeric ranges ---
string[] segments = [.. trimmed.Split([".."], StringSplitOptions.None).Select(s => s.Trim())];
// Check for empty segments (e.g., from "1...2")
bool hasEmptySegment = segments.Take(segments.Length - 1).Any(s => string.IsNullOrEmpty(s));
if (hasEmptySegment)
{
// If there's an invalid ellipsis, treat the whole part as a single text value
values.Add(trimmed);
}
else if (segments.Length >= 2)
{
// Try to parse as a numeric range
if (double.TryParse(segments[0], NumberStyles.Float, CultureInfo.InvariantCulture, out double start) &&
double.TryParse(segments[1], NumberStyles.Float, CultureInfo.InvariantCulture, out double end))
{
// It's a valid numeric range, expand it
double step = 1.0;
if (segments.Length > 2 &&
double.TryParse(segments[2], NumberStyles.Float, CultureInfo.InvariantCulture, out double parsedStep))
{
step = Math.Abs(parsedStep);
if (step == 0)
{
step = 1.0;
}
}
if (start <= end)
{
for (double i = start; Math.Round(i, 6) <= end; i += step)
{
values.Add(Math.Round(i, 6).ToString(CultureInfo.InvariantCulture));
}
}
else
{
for (double i = start; Math.Round(i, 6) >= end; i -= step)
{
values.Add(Math.Round(i, 6).ToString(CultureInfo.InvariantCulture));
}
}
}
else
{
// Not a numeric range, treat each non-empty segment as a text value
foreach (string? segment in segments)
{
if (!string.IsNullOrEmpty(segment))
{
values.Add(segment);
}
}
}
}
else
{
// Edge case, add the whole trimmed string
values.Add(trimmed);
}
}
else
{
// --- Handle explicit text values, INCLUDING empty ones ---
// Add the trimmed string, even if it's empty
values.Add(trimmed);
}
}
// Remove duplicates (empty strings are also considered)
return [.. values.Distinct()];
}
/// <summary>
/// Compares strings using natural sorting (e.g., "file2.txt" before "file10.txt").
/// Ensures parameters like 1.2 appear before 1.10 in output.
/// </summary>
private class NaturalStringComparer : IComparer<string?>
{
public int Compare(string? x, string? y)
{
return x == null && y == null ? 0 : x == null ? -1 : y == null ? 1 : CompareNatural(x, y);
}
private static int CompareNatural(string strA, string strB)
{
int i1 = 0, i2 = 0;
while (i1 < strA.Length && i2 < strB.Length)
{
if (char.IsDigit(strA[i1]) || char.IsDigit(strB[i2]))
{
// Parse numbers (including decimals)
bool hasDecimalA = false, hasDecimalB = false;
long wholeA = 0, wholeB = 0;
long fracA = 0, fracB = 0;
int fracDigitsA = 0, fracDigitsB = 0;
// Parse first number
while (i1 < strA.Length)
{
char c = strA[i1];
if (c == '.' && !hasDecimalA)
{
hasDecimalA = true;
i1++;
continue;
}
else if (char.IsDigit(c))
{
if (hasDecimalA)
{
fracA = (fracA * 10) + (c - '0');
fracDigitsA++;
}
else
{
wholeA = (wholeA * 10) + (c - '0');
}
i1++;
}
else
{
break;
}
}
// Parse second number
while (i2 < strB.Length)
{
char c = strB[i2];
if (c == '.' && !hasDecimalB)
{
hasDecimalB = true;
i2++;
continue;
}
else if (char.IsDigit(c))
{
if (hasDecimalB)
{
fracB = (fracB * 10) + (c - '0');
fracDigitsB++;
}
else
{
wholeB = (wholeB * 10) + (c - '0');
}
i2++;
}
else
{
break;
}
}
// Normalize fractional parts to same scale
int maxFracDigits = Math.Max(fracDigitsA, fracDigitsB);
long scaledA = (wholeA * (long)Math.Pow(10, maxFracDigits)) +
(fracA * (long)Math.Pow(10, maxFracDigits - fracDigitsA));
long scaledB = (wholeB * (long)Math.Pow(10, maxFracDigits)) +
(fracB * (long)Math.Pow(10, maxFracDigits - fracDigitsB));
if (scaledA != scaledB)
{
return scaledA.CompareTo(scaledB);
}
}
else
{
int result = char.ToLowerInvariant(strA[i1]).CompareTo(char.ToLowerInvariant(strB[i2]));
if (result != 0)
{
return result;
}
i1++;
i2++;
}
}
return strA.Length.CompareTo(strB.Length);
}
}
}
}