-
-
Notifications
You must be signed in to change notification settings - Fork 63
/
Utils.cs
524 lines (469 loc) · 21.1 KB
/
Utils.cs
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
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
using ATL;
using System;
using System.Globalization;
using System.Text;
using System.Collections.Generic;
using System.IO;
namespace Commons
{
/// <summary>
/// General utility class
/// </summary>
internal static class Utils
{
private static Encoding latin1Encoding = Encoding.GetEncoding("ISO-8859-1");
private static IDictionary<string, Encoding> encodingCache = new Dictionary<string, Encoding>();
private static CultureInfo enUsCulture = CultureInfo.CreateSpecificCulture("en-US");
/// <summary>
/// 'ZERO WIDTH NO-BREAK SPACE' invisible character, sometimes used by certain tagging softwares
/// Looks like a BOM unfortunately converted into an unicode character :/
/// </summary>
public readonly static string UNICODE_INVISIBLE_EMPTY = "\uFEFF";
/// <summary>
/// Define a delegate that does not carry any argument (useful for "pinging")
/// </summary>
public delegate void voidDelegate();
/// <summary>
/// ISO-8859-1 encoding
/// </summary>
public static Encoding Latin1Encoding { get { return latin1Encoding; } }
/// <summary>
/// en-US culture
/// </summary>
public static CultureInfo EnUsCulture { get { return enUsCulture; } }
/// <summary>
/// Transform the given string so that is becomes non-null
/// </summary>
/// <param name="value">String to protect</param>
/// <returns>Given string if non-null; else empty string</returns>
public static string ProtectValue(string value)
{
return (null == value) ? "" : value;
}
/// <summary>
/// Extract the year from the given DateTime; "" if DateTime is its minimum value
/// </summary>
/// <param name="value">DateTime to extract the year from</param>
/// <returns>Year from the given DateTime, or "" if not set</returns>
public static string ProtectYear(DateTime value)
{
return (DateTime.MinValue == value) ? "" : value.Year.ToString();
}
/// <summary>
/// Format the given duration using the following format
/// DDdHH:MM:SS.UUUU
///
/// Where
/// DD is the number of days, if applicable (i.e. durations of less than 1 day won't display the "DDd" part)
/// HH is the number of hours, if applicable (i.e. durations of less than 1 hour won't display the "HH:" part)
/// MM is the number of minutes
/// SS is the number of seconds
/// UUUU is the number of milliseconds
/// </summary>
/// <param name="milliseconds">Duration to format (in milliseconds)</param>
/// <returns>Formatted duration according to the abovementioned convention</returns>
public static string EncodeTimecode_ms(long milliseconds)
{
long seconds = Convert.ToInt64(Math.Floor(milliseconds / 1000.00));
return EncodeTimecode_s(seconds) + "." + (milliseconds - seconds * 1000);
}
/// <summary>
/// Format the given duration using the following format
/// DDdHH:MM:SS
///
/// Where
/// DD is the number of days, if applicable (i.e. durations of less than 1 day won't display the "DDd" part)
/// HH is the number of hours, if applicable (i.e. durations of less than 1 hour won't display the "HH:" part)
/// MM is the number of minutes
/// SS is the number of seconds
/// </summary>
/// <param name="seconds">Duration to format (in seconds)</param>
/// <returns>Formatted duration according to the abovementioned convention</returns>
public static string EncodeTimecode_s(long seconds)
{
int h;
long m;
String hStr, mStr, sStr;
long s;
int d;
h = Convert.ToInt32(Math.Floor(seconds / 3600.00));
m = Convert.ToInt64(Math.Floor((seconds - 3600.00 * h) / 60));
s = seconds - (60 * m) - (3600 * h);
d = Convert.ToInt32(Math.Floor(h / 24.00));
if (d > 0) h = h - (24 * d);
hStr = h.ToString();
if (1 == hStr.Length) hStr = "0" + hStr;
mStr = m.ToString();
if (1 == mStr.Length) mStr = "0" + mStr;
sStr = s.ToString();
if (1 == sStr.Length) sStr = "0" + sStr;
if (d > 0)
{
return d + "d " + hStr + ":" + mStr + ":" + sStr;
}
else
{
if (h > 0)
{
return hStr + ":" + mStr + ":" + sStr;
}
else
{
return mStr + ":" + sStr;
}
}
}
/// <summary>
/// Convert the duration of the given timecode to milliseconds
/// Supported formats : hh:mm, hh:mm:ss.ddd, mm:ss, hh:mm:ss and mm:ss.ddd
/// </summary>
/// <param name="timeCode">Timecode to convert</param>
/// <returns>Duration of the given timecode expressed in milliseconds if succeeded; -1 if failed</returns>
static public int DecodeTimecodeToMs(string timeCode)
{
int result = -1;
DateTime dateTime;
bool valid = false;
if (DateTime.TryParse(timeCode, out dateTime)) // Handle classic cases hh:mm, hh:mm:ss.ddd (the latter being the spec)
{
valid = true;
result = dateTime.Millisecond;
result += dateTime.Second * 1000;
result += dateTime.Minute * 60 * 1000;
result += dateTime.Hour * 60 * 60 * 1000;
}
else // Handle mm:ss, hh:mm:ss and mm:ss.ddd
{
int days = 0;
int hours = 0;
int minutes = 0;
int seconds = 0;
int milliseconds = 0;
if (timeCode.Contains(":"))
{
valid = true;
string[] parts = timeCode.Split(':');
if (parts[parts.Length - 1].Contains("."))
{
string[] subPart = parts[parts.Length - 1].Split('.');
parts[parts.Length - 1] = subPart[0];
milliseconds = int.Parse(subPart[1]);
}
seconds = int.Parse(parts[parts.Length - 1]);
minutes = int.Parse(parts[parts.Length - 2]);
if (parts.Length >= 3)
{
string[] subPart = parts[parts.Length - 3].Split('d');
if (subPart.Length > 1)
{
days = int.Parse(subPart[0].Trim());
hours = int.Parse(subPart[1].Trim());
}
else
{
hours = int.Parse(subPart[0]);
}
}
result = milliseconds;
result += seconds * 1000;
result += minutes * 60 * 1000;
result += hours * 60 * 60 * 1000;
result += days * 24 * 60 * 60 * 1000;
}
}
if (!valid) result = -1;
return result;
}
/// <summary>
/// Strip the given string from all ending null '\0' characters
/// </summary>
/// <param name="iStr">String to process</param>
/// <returns>Given string, without any ending null character</returns>
public static string StripEndingZeroChars(string iStr)
{
//return Regex.Replace(iStr, @"\0+\Z", ""); Too expensive
int i = iStr.Length;
while (i > 0 && '\0' == iStr[i - 1]) i--;
return iStr.Substring(0, i);
}
/// <summary>
/// Transform the given number to format with the given length, expressed in number of characters
/// - If the given length is shorter than the actual length of the string, it will be truncated
/// - If the given length is longer than the actual length of the string, it will be right/left-padded with a given character
/// </summary>
/// <param name="value">Value to transform</param>
/// <param name="length">Target length of the final string</param>
/// <param name="paddingChar">Character to use if padding is needed</param>
/// <param name="padRight">True if the padding has to be done on the right-side of the target string;
/// false if the padding has to be done on the left-side (optional; default value = true)</param>
/// <returns>Reprocessed string of given length, according to rules documented in the method description</returns>
public static string BuildStrictLengthString(int value, int length, char paddingChar, bool padRight = true)
{
return BuildStrictLengthString(value.ToString(), length, paddingChar, padRight);
}
/// <summary>
/// Transform the given string to format with the given length, expressed in number of characters
/// - If the given length is shorter than the actual length of the string, it will be truncated
/// - If the given length is longer than the actual length of the string, it will be right/left-padded with a given character
/// </summary>
/// <param name="value">Value to transform</param>
/// <param name="length">Target length of the final string</param>
/// <param name="paddingChar">Character to use if padding is needed</param>
/// <param name="padRight">True if the padding has to be done on the right-side of the target string;
/// false if the padding has to be done on the left-side (optional; default value = true)</param>
/// <returns>Reprocessed string of given length, according to rules documented in the method description</returns>
public static string BuildStrictLengthString(string value, int length, char paddingChar, bool padRight = true)
{
string result = (null == value) ? "" : value;
if (result.Length > length) result = result.Substring(0, length);
else if (result.Length < length)
{
if (padRight) result = result.PadRight(length, paddingChar);
else result = result.PadLeft(length, paddingChar);
}
return result;
}
/// <summary>
/// Transform the given string to format with the given length, expressed in number of bytes
/// - If the given length is shorter than the actual length of the string, it will be truncated
/// - If the given length is longer than the actual length of the string, it will be right/left-padded with a given byte
/// </summary>
/// <param name="value">String to transform</param>
/// <param name="targetLength">Target length of the final string</param>
/// <param name="paddingByte">Byte to use if padding is needed</param>
/// <param name="encoding">Encoding to use to represent the given string in binary format</param>
/// <param name="padRight">True if the padding has to be done on the right-side of the target string;
/// false if the padding has to be done on the left-side (optional; default value = true)</param>
/// <returns>Reprocessed string of given length, in binary format, according to rules documented in the method description</returns>
public static byte[] BuildStrictLengthStringBytes(string value, int targetLength, byte paddingByte, Encoding encoding, bool padRight = true)
{
byte[] result;
byte[] data = encoding.GetBytes(value);
while (data.Length > targetLength)
{
value = value.Remove(value.Length - 1);
data = encoding.GetBytes(value);
}
if (data.Length < targetLength)
{
result = new byte[targetLength];
if (padRight)
{
Array.Copy(data, result, data.Length);
for (int i = data.Length; i < result.Length; i++) result[i] = paddingByte;
}
else
{
Array.Copy(data, 0, result, result.Length - data.Length, data.Length);
for (int i = 0; i < (result.Length - data.Length); i++) result[i] = paddingByte;
}
}
else
{
result = data;
}
return result;
}
/// <summary>
/// Covert given string value to boolean.
/// - Returns true if string represents a non-null numeric value or the word "true"
/// - Returns false if not
///
/// NB : This implementation exists because default .NET implementation has a different convention as for parsing numbers
/// </summary>
/// <param name="value">Value to be converted</param>
/// <returns>Resulting boolean value</returns>
public static bool ToBoolean(string value)
{
if (value != null)
{
value = value.Trim();
if (value.Length > 0)
{
// Numeric convert
float f;
if (float.TryParse(value, out f))
{
return (f != 0);
}
else
{
value = value.ToLower();
return ("true".Equals(value));
}
}
}
return false;
}
/// <summary>
/// Decode the given Base64 string
/// Source : http://blogs.microsoft.co.il/blogs/mneiter/archive/2009/03/22/how-to-encoding-and-decoding-base64-strings-in-c.aspx
/// </summary>
/// <param name="encodedData">String containing the characters to decode</param>
/// <returns>Decoded data</returns>
public static byte[] DecodeFrom64(byte[] encodedData)
{
if (encodedData.Length % 4 > 0) throw new FormatException("Size must me multiple of 4");
char[] encodedDataChar = new char[encodedData.Length];
Latin1Encoding.GetChars(encodedData, 0, encodedData.Length, encodedDataChar, 0); // Optimized for large data
return System.Convert.FromBase64CharArray(encodedDataChar, 0, encodedDataChar.Length);
}
/// <summary>
/// Convert the given input to a Base64 UUencoded output
/// </summary>
/// <param name="data">Data to be encoded</param>
/// <returns>Encoded data</returns>
public static byte[] EncodeTo64(byte[] data)
{
// Each 3 byte sequence in the source data becomes a 4 byte
// sequence in the character array.
long arrayLength = (long)((4.0d / 3.0d) * data.Length);
// If array length is not divisible by 4, go up to the next
// multiple of 4.
if (arrayLength % 4 != 0)
{
arrayLength += 4 - arrayLength % 4;
}
char[] dataChar = new char[arrayLength];
System.Convert.ToBase64CharArray(data, 0, data.Length, dataChar, 0);
return Utils.Latin1Encoding.GetBytes(dataChar);
}
/// <summary>
/// Indicate if the given string is exclusively composed of digital characters
///
/// NB1 : decimal separators '.' and ',' are tolerated except if allowsOnlyIntegers argument is set to True
/// NB2 : whitespaces ' ' are not tolerated
/// NB3 : any alternate notation (e.g. exponent, hex) is not tolerated
/// </summary>
/// <param name="s">String to analyze</param>
/// <param name="allowsOnlyIntegers">Set to True if IsNumeric should reject decimal values; default = false</param>
/// <returns>True if the string is a digital value; false if not</returns>
public static bool IsNumeric(string s, bool allowsOnlyIntegers = false)
{
if ((null == s) || (0 == s.Length)) return false;
for (int i = 0; i < s.Length; i++)
{
if ((s[i] == '.') || (s[i] == ','))
{
if (allowsOnlyIntegers) return false;
}
else
{
if (!char.IsDigit(s[i]) && (s[i] != '-')) return false;
}
}
return true;
}
/// <summary>
/// Indicate if the given character represents a non-decimal digit (0..9)
/// </summary>
/// <param name="c">Character to analyze</param>
/// <returns>True if char is between 0..9; false instead</returns>
public static bool IsDigit(char c)
{
return (c >= '0' && c <= '9');
}
/// <summary>
/// Indicate if the given string is hexadecimal notation
/// </summary>
/// <param name="s">String to analyze</param>
/// <returns>True if the string is a hexadecimal notation; false if not</returns>
public static bool IsHex(string s)
{
if ((null == s) || (0 == s.Length)) return false;
if (s.Length % 2 > 0) return false; // Hex notation always uses two characters for every byte
char c;
for (int i = 0; i < s.Length; i++)
{
c = char.ToUpper(s[i]);
if (!char.IsDigit(c) && c != 'A' && c != 'B' && c != 'C' && c != 'D' && c != 'E' && c != 'F') return false;
}
return true;
}
/// <summary>
/// Parse the given string into a float value; returns 0 if parsing fails
/// </summary>
/// <param name="s">String to be parsed</param>
/// <returns>Parsed value; 0 if a parsing issue has been encountered</returns>
public static double ParseDouble(string s)
{
if (!IsNumeric(s)) return 0;
string[] parts = s.Split(new char[] { ',', '.' });
if (parts.Length > 2) return 0;
else if (1 == parts.Length) return double.Parse(s);
else // 2 == parts.Length
{
double decimalDivisor = Math.Pow(10, parts[1].Length);
double result = double.Parse(parts[0]);
if (result >= 0) return result + double.Parse(parts[1]) / decimalDivisor;
else return result - double.Parse(parts[1]) / decimalDivisor;
}
}
/// <summary>
/// Return the human-readable file size for an arbitrary, 64-bit file size
/// The default format is "0.### XB", e.g. "4.2 KB" or "1.434 GB"
/// Source : https://www.somacon.com/p576.php
/// </summary>
/// <param name="i">Size to display in a human-readable form</param>
/// <returns>Given size displayed in a human-readable form</returns>
public static string GetBytesReadable(long i)
{
// Get absolute value
long absolute_i = (i < 0 ? -i : i);
// Determine the suffix and readable value
string suffix;
double readable;
if (absolute_i >= 0x1000000000000000) // Exabyte
{
suffix = "EB";
readable = (i >> 50);
}
else if (absolute_i >= 0x4000000000000) // Petabyte
{
suffix = "PB";
readable = (i >> 40);
}
else if (absolute_i >= 0x10000000000) // Terabyte
{
suffix = "TB";
readable = (i >> 30);
}
else if (absolute_i >= 0x40000000) // Gigabyte
{
suffix = "GB";
readable = (i >> 20);
}
else if (absolute_i >= 0x100000) // Megabyte
{
suffix = "MB";
readable = (i >> 10);
}
else if (absolute_i >= 0x400) // Kilobyte
{
suffix = "KB";
readable = i;
}
else
{
return i.ToString("0 B"); // Byte
}
// Divide by 1024 to get fractional value
readable = (readable / 1024);
// Return formatted number with suffix
return readable.ToString("0.## ") + suffix;
}
private static Encoding getEncodingCached(string code)
{
if (!encodingCache.ContainsKey(code)) encodingCache[code] = Encoding.GetEncoding(code);
return encodingCache[code];
}
public static Encoding guessTextEncoding(FileStream fs)
{
Ude.CharsetDetector cdet = new Ude.CharsetDetector();
cdet.Feed(fs);
cdet.DataEnd();
if (cdet.Charset != null) return getEncodingCached(cdet.Charset);
else return Settings.DefaultTextEncoding;
}
}
}