-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathUtil.cs
551 lines (490 loc) · 15.7 KB
/
Util.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
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using ToVPatcher;
namespace HyoutaTools {
public static class Util {
public static string exeSuffix = "";
#region SwapEndian
public static Int16 SwapEndian( this Int16 x ) {
return (Int16)SwapEndian( (UInt16)x );
}
public static UInt16 SwapEndian( this UInt16 x ) {
return x = (UInt16)
( ( x << 8 ) |
( x >> 8 ) );
}
public static Int32 SwapEndian( this Int32 x ) {
return (Int32)SwapEndian( (UInt32)x );
}
public static UInt32 SwapEndian( this UInt32 x ) {
return x = ( x << 24 ) |
( ( x << 8 ) & 0x00FF0000 ) |
( ( x >> 8 ) & 0x0000FF00 ) |
( x >> 24 );
}
public static Int64 SwapEndian( this Int64 x ) {
return (Int64)SwapEndian( (UInt64)x );
}
public static UInt64 SwapEndian( this UInt64 x ) {
return x = ( x << 56 ) |
( ( x << 40 ) & 0x00FF000000000000 ) |
( ( x << 24 ) & 0x0000FF0000000000 ) |
( ( x << 8 ) & 0x000000FF00000000 ) |
( ( x >> 8 ) & 0x00000000FF000000 ) |
( ( x >> 24 ) & 0x0000000000FF0000 ) |
( ( x >> 40 ) & 0x000000000000FF00 ) |
( x >> 56 );
}
#endregion
#region HexUtils
public static byte ParseDecOrHexToByte( string s ) {
s = s.Trim();
if ( s.StartsWith( "0x" ) ) {
s = s.Substring( 2 );
return Byte.Parse( s, System.Globalization.NumberStyles.HexNumber );
} else {
return Byte.Parse( s );
}
}
public static uint ParseDecOrHex( string s ) {
s = s.Trim();
if ( s.StartsWith( "0x" ) ) {
s = s.Substring( 2 );
return UInt32.Parse( s, System.Globalization.NumberStyles.HexNumber );
} else {
return UInt32.Parse( s );
}
}
public static byte[] HexStringToByteArray( string hex ) {
if ( hex.Length % 2 == 1 )
throw new Exception( "The binary key cannot have an odd number of digits" );
byte[] arr = new byte[hex.Length >> 1];
for ( int i = 0; i < hex.Length >> 1; ++i ) {
arr[i] = (byte)( ( GetHexVal( hex[i << 1] ) << 4 ) + ( GetHexVal( hex[( i << 1 ) + 1] ) ) );
}
return arr;
}
public static int GetHexVal( char hex ) {
int val = (int)hex;
//For uppercase A-F letters:
//return val - (val < 58 ? 48 : 55);
//For lowercase a-f letters:
//return val - (val < 58 ? 48 : 87);
//Or the two combined, but a bit slower:
return val - ( val < 58 ? 48 : ( val < 97 ? 55 : 87 ) );
}
#endregion
#region NumberUtils
public static uint ToUInt24( byte[] File, int Pointer ) {
byte b1 = File[Pointer];
byte b2 = File[Pointer + 1];
byte b3 = File[Pointer + 2];
return (uint)( b3 << 16 | b2 << 8 | b1 );
}
public static byte[] GetBytesForUInt24( uint Number ) {
byte[] b = new byte[3];
b[0] = (byte)( Number & 0xFF );
b[1] = (byte)( ( Number >> 8 ) & 0xFF );
b[2] = (byte)( ( Number >> 16 ) & 0xFF );
return b;
}
/// <summary>
/// converts a 32-bit int that's actually a byte representation of a float
/// to an actual float for use in calculations or whatever
/// </summary>
public static float UIntToFloat( this uint integer ) {
byte[] b = BitConverter.GetBytes( integer );
float f = BitConverter.ToSingle( b, 0 );
return f;
}
public static int Align( this int Number, int Alignment ) {
return (int)Align( (uint)Number, (uint)Alignment );
}
public static uint Align( this uint Number, uint Alignment ) {
uint diff = Number % Alignment;
if ( diff == 0 ) {
return Number;
} else {
return ( Number + ( Alignment - diff ) );
}
}
public static long Align( this long Number, int Alignment ) {
return (long)Align( (ulong)Number, (uint)Alignment );
}
public static ulong Align( this ulong Number, uint Alignment ) {
ulong diff = Number % Alignment;
if ( diff == 0 ) {
return Number;
} else {
return ( Number + ( Alignment - diff ) );
}
}
#endregion
#region TextUtils
private static Encoding _ShiftJISEncoding = null;
public static Encoding ShiftJISEncoding { get { if ( _ShiftJISEncoding == null ) { _ShiftJISEncoding = Encoding.GetEncoding( 932 ); } return _ShiftJISEncoding; } }
public static String GetTextShiftJis( byte[] File, int Pointer ) {
if ( Pointer == -1 ) return null;
try {
int i = Pointer;
while ( File[i] != 0x00 ) {
i++;
}
String Text = ShiftJISEncoding.GetString( File, Pointer, i - Pointer );
return Text;
} catch ( Exception ) {
return null;
}
}
public static String GetTextAscii( byte[] File, int Pointer ) {
if ( Pointer == -1 ) return null;
try {
int i = Pointer;
while ( File[i] != 0x00 ) {
i++;
}
String Text = Encoding.ASCII.GetString( File, Pointer, i - Pointer );
return Text;
} catch ( Exception ) {
return null;
}
}
public static String GetTextUnicode( byte[] File, int Pointer, int MaxByteLength ) {
StringBuilder sb = new StringBuilder();
for ( int i = 0; i < MaxByteLength; i += 2 ) {
ushort ch = BitConverter.ToUInt16( File, Pointer + i );
if ( ch == 0 || ch == 0xFFFF ) { break; }
sb.Append( (char)ch );
}
return sb.ToString();
}
public static String GetTextUTF8( byte[] File, int Pointer ) {
int tmp;
return GetTextUTF8( File, Pointer, out tmp );
}
public static String GetTextUTF8( byte[] File, int Pointer, out int NullLocation ) {
if ( Pointer == -1 ) { NullLocation = -1; return null; }
try {
int i = Pointer;
while ( File[i] != 0x00 ) {
i++;
}
String Text = Encoding.UTF8.GetString( File, Pointer, i - Pointer );
NullLocation = i;
return Text;
} catch ( Exception ) {
NullLocation = -1;
return null;
}
}
public static String TrimNull( this String s ) {
int n = s.IndexOf( '\0', 0 );
if ( n >= 0 ) {
return s.Substring( 0, n );
}
return s;
}
public static byte[] StringToBytesShiftJis( String s ) {
//byte[] bytes = ShiftJISEncoding.GetBytes(s);
//return bytes.TakeWhile(subject => subject != 0x00).ToArray();
return ShiftJISEncoding.GetBytes( s );
}
public static byte[] StringToBytesUTF16( String s ) {
return Encoding.Unicode.GetBytes( s );
}
public static string XmlEscape( string s ) {
s = s.Replace( "&", "&" );
s = s.Replace( "\"", """ );
s = s.Replace( "'", "'" );
s = s.Replace( "<", "<" );
s = s.Replace( ">", ">" );
return s;
}
public static string Truncate( this string value, int maxLength ) {
if ( string.IsNullOrEmpty( value ) ) return value;
return value.Length <= maxLength ? value : value.Substring( 0, maxLength );
}
#endregion
#region TimeUtils
public static DateTime UnixTimeToDateTime( ulong unixTime ) {
return new DateTime( 1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc ).AddSeconds( unixTime ).ToLocalTime();
}
public static ulong DateTimeToUnixTime( DateTime time ) {
return (ulong)( time - new DateTime( 1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc ).ToLocalTime() ).TotalSeconds;
}
public static DateTime PS3TimeToDateTime( ulong PS3Time ) {
return new DateTime( 1, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc ).AddMilliseconds( PS3Time / 1000 ).ToLocalTime();
}
#endregion
#region ProgramUtils
public static bool RunProgram( String prog, String args, bool displayCommandLine, bool displayOutput, bool useShell = false ) {
if ( displayCommandLine ) {
Console.Write( prog );
Console.Write( " " );
Console.WriteLine( args );
}
// Use ProcessStartInfo class
System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
startInfo.CreateNoWindow = false;
startInfo.UseShellExecute = useShell;
startInfo.FileName = prog;
startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
startInfo.Arguments = args;
startInfo.RedirectStandardOutput = !useShell;
startInfo.RedirectStandardError = !useShell;
//startInfo.RedirectStandardInput = !useShell;
//startInfo.UserName = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
using ( System.Diagnostics.Process exeProcess = System.Diagnostics.Process.Start( startInfo ) ) {
exeProcess.WaitForExit();
if ( useShell ) {
return exeProcess.ExitCode == 0;
}
string output;
string err;
output = exeProcess.StandardOutput.ReadToEnd();
err = exeProcess.StandardError.ReadToEnd();
int exitCode = exeProcess.ExitCode;
if ( exitCode != 0 ) {
Console.WriteLine( prog + " returned nonzero:" );
Console.WriteLine( output );
throw new Exception( output );
//return false;
}
if ( displayOutput ) {
Console.WriteLine( output );
Console.WriteLine( err );
}
return true;
}
}
#endregion
#region ArrayUtils
public static void CopyByteArrayPart( IList<byte> from, int locationFrom, IList<byte> to, int locationTo, int count ) {
for ( int i = 0; i < count; i++ ) {
to[locationTo + i] = from[locationFrom + i];
}
}
public static void FillNull( IList<byte> Array, int Location, int Count ) {
for ( int i = 0; i < Count; ++i ) {
Array[Location + i] = 0x00;
}
}
public static bool IsByteArrayPartEqual( IList<byte> Array1, int Location1, IList<byte> Array2, int Location2, int count ) {
for ( int i = 0; i < count; ++i ) {
if ( Array1[i + Location1] != Array2[i + Location2] ) {
return false;
}
}
return true;
}
#endregion
#region StreamUtils
public static void CopyStream( System.IO.Stream input, System.IO.Stream output, int count ) {
byte[] buffer = new byte[4096];
int read;
int bytesLeft = count;
while ( ( read = input.Read( buffer, 0, Math.Min( buffer.Length, bytesLeft ) ) ) > 0 ) {
output.Write( buffer, 0, read );
bytesLeft -= read;
if ( bytesLeft <= 0 ) return;
}
}
public static bool IsIdentical( this Stream str, Stream other, long count ) {
for ( long i = 0; i < count; ++i ) {
if ( str.ReadByte() != other.ReadByte() ) {
return false;
}
}
return true;
}
public static uint ReadUInt32( this Stream s ) {
int b1 = s.ReadByte();
int b2 = s.ReadByte();
int b3 = s.ReadByte();
int b4 = s.ReadByte();
return (uint)( b4 << 24 | b3 << 16 | b2 << 8 | b1 );
}
public static uint PeekUInt32( this Stream s ) {
long pos = s.Position;
uint retval = s.ReadUInt32();
s.Position = pos;
return retval;
}
public static void WriteUInt32( this Stream s, uint num ) {
s.Write( BitConverter.GetBytes( num ), 0, 4 );
}
public static uint ReadUInt24( this Stream s ) {
int b1 = s.ReadByte();
int b2 = s.ReadByte();
int b3 = s.ReadByte();
return (uint)( b3 << 16 | b2 << 8 | b1 );
}
public static uint PeekUInt24( this Stream s ) {
long pos = s.Position;
uint retval = s.ReadUInt24();
s.Position = pos;
return retval;
}
public static ushort ReadUInt16( this Stream s ) {
int b1 = s.ReadByte();
int b2 = s.ReadByte();
return (ushort)( b2 << 8 | b1 );
}
public static ushort PeekUInt16( this Stream s ) {
long pos = s.Position;
ushort retval = s.ReadUInt16();
s.Position = pos;
return retval;
}
public static void DiscardBytes( this Stream s, uint count ) {
s.Position = s.Position + count;
}
public static void WriteUInt16( this Stream s, ushort num ) {
s.Write( BitConverter.GetBytes( num ), 0, 2 );
}
public static string ReadAsciiNullterm( this Stream s ) {
StringBuilder sb = new StringBuilder();
int b = s.ReadByte();
while ( b != 0 && b != -1 ) {
sb.Append( (char)( b ) );
b = s.ReadByte();
}
return sb.ToString();
}
public static string ReadAscii( this Stream s, int count ) {
StringBuilder sb = new StringBuilder( count );
int b;
for ( int i = 0; i < count; ++i ) {
b = s.ReadByte();
sb.Append( (char)( b ) );
}
return sb.ToString();
}
public static string ReadUTF16Nullterm( this Stream s ) {
StringBuilder sb = new StringBuilder();
byte[] b = new byte[2];
int b0 = s.ReadByte();
int b1 = s.ReadByte();
while ( !( b0 == 0 && b1 == 0 ) && b1 != -1 ) {
b[0] = (byte)b0; b[1] = (byte)b1;
sb.Append( Encoding.Unicode.GetString( b, 0, 2 ) );
b0 = s.ReadByte(); b1 = s.ReadByte();
}
return sb.ToString();
}
public static string ReadShiftJisNullterm( this Stream s ) {
StringBuilder sb = new StringBuilder();
byte[] buffer = new byte[2];
int b = s.ReadByte();
while ( b != 0 && b != -1 ) {
if ( ( b >= 0 && b <= 0x80 ) || ( b >= 0xA0 && b <= 0xDF ) ) {
// is a single byte
buffer[0] = (byte)b;
sb.Append( ShiftJISEncoding.GetString( buffer, 0, 1 ) );
} else {
// is two bytes
buffer[0] = (byte)b;
buffer[1] = (byte)s.ReadByte();
sb.Append( ShiftJISEncoding.GetString( buffer ) );
}
b = s.ReadByte();
}
return sb.ToString();
}
public static void Write( this Stream s, byte[] data ) {
s.Write( data, 0, data.Length );
}
#endregion
public static string GuessFileExtension( Stream s ) {
uint magic32 = s.PeekUInt32();
uint magic24 = s.PeekUInt24();
uint magic16 = s.PeekUInt16();
switch ( magic32 ) {
case 0x46464952:
return ".wav";
case 0x474E5089:
return ".png";
case 0x5367674F:
return ".ogg";
}
switch ( magic16 ) {
case 0x4D42:
return ".bmp";
}
return "";
}
public static void Assert( bool cond ) {
if ( !cond ) {
throw new Exception( "Assert Failed!" );
}
}
public static TValue GetValueOrDefault<TKey, TValue>( this IDictionary<TKey, TValue> dictionary, TKey key, TValue defaultValue ) {
TValue value;
return dictionary.TryGetValue( key, out value ) ? value : defaultValue;
}
public static void DeleteDirectoryAggressive( string path, bool recursive = true ) {
if ( !recursive ) { Directory.Delete( path ); return; }
for ( int i = 0; i < 16; ++i ) {
try {
Directory.Delete( path, true );
} catch ( IOException ) {
} catch ( UnauthorizedAccessException ) {
}
System.Threading.Thread.Sleep( 1 );
if ( !Directory.Exists( path ) ) { return; }
}
Directory.Delete( path, true );
}
public static string[] DirectoryGetFilesWorkaround( string dirpath, bool logFiles = false ) {
string[] files = Directory.GetFiles( dirpath );
string[] fixedFiles = FixFrenchLocaleBugMaybe( files );
if ( logFiles ) {
Logger.LogPatching( "Fetching directory '" + dirpath + "', got " + files.Length + " files:" );
LogFiles( fixedFiles );
}
return fixedFiles;
}
public static string[] DirectoryGetFilesWorkaround( string dirpath, string searchPattern, SearchOption searchOption, bool logFiles = false ) {
string[] files = Directory.GetFiles( dirpath, searchPattern, searchOption );
string[] fixedFiles = FixFrenchLocaleBugMaybe( files );
if ( logFiles ) {
Logger.LogPatching( "Fetching directory '" + dirpath + "' with filter, got " + files.Length + " files:" );
LogFiles( fixedFiles );
}
return fixedFiles;
}
// fixes super weird bug seen on a french windows locale that adds ._ in front of filenames from Directory.GetFiles
public static string[] FixFrenchLocaleBugMaybe( string[] files ) {
for ( int i = 0; i < files.Length; ++i ) {
string path = files[i];
string dir = Path.GetDirectoryName( path );
string name = Path.GetFileName( path );
if ( name.StartsWith( "." ) ) {
name = name.TrimStart( new char[] { '.', '_' } );
files[i] = Path.Combine( dir, name );
}
}
return files;
}
public static void LogFiles( string[] files ) {
for ( int i = 0; i < files.Length; ++i ) {
Logger.LogFileData( files[i] );
}
}
/// <summary>
/// Checks if running on Windows
/// </summary>
/// <returns><c>true</c>, if running on windows <c>false</c> otherwise.</returns>
public static bool isRunningOnWindows() {
OperatingSystem os = Environment.OSVersion;
PlatformID pid = os.Platform;
if (pid == PlatformID.Unix || pid == PlatformID.MacOSX) {
return false;
}
return true;
}
}
}