You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

189 lines
7.8 KiB

6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
  1. using System;
  2. using System.IO;
  3. using System.Text;
  4. #if NET3
  5. using File = Net3_Proxy.File;
  6. #endif
  7. namespace IPA.Utilities
  8. {
  9. /// <summary>
  10. /// A class providing static utility functions that in any other language would just *exist*.
  11. /// </summary>
  12. public static class Utils
  13. {
  14. /// <summary>
  15. /// Converts a hex string to a byte array.
  16. /// </summary>
  17. /// <param name="hex">the hex stream</param>
  18. /// <returns>the corresponding byte array</returns>
  19. public static byte[] StringToByteArray(string hex)
  20. {
  21. int numberChars = hex.Length;
  22. byte[] bytes = new byte[numberChars / 2];
  23. for (int i = 0; i < numberChars; i += 2)
  24. bytes[i / 2] = Convert.ToByte(hex.Substring(i, 2), 16);
  25. return bytes;
  26. }
  27. /// <summary>
  28. /// Converts a byte array to a hex string.
  29. /// </summary>
  30. /// <param name="ba">the byte array</param>
  31. /// <returns>the hex form of the array</returns>
  32. public static string ByteArrayToString(byte[] ba)
  33. {
  34. StringBuilder hex = new StringBuilder(ba.Length * 2);
  35. foreach (byte b in ba)
  36. hex.AppendFormat("{0:x2}", b);
  37. return hex.ToString();
  38. }
  39. // Copyright (c) 2008-2013 Hafthor Stefansson
  40. // Distributed under the MIT/X11 software license
  41. // Ref: http://www.opensource.org/licenses/mit-license.php.
  42. // From: https://stackoverflow.com/a/8808245/3117125
  43. /// <summary>
  44. /// Uses unsafe code to compare 2 byte arrays quickly.
  45. /// </summary>
  46. /// <param name="a1">array 1</param>
  47. /// <param name="a2">array 2</param>
  48. /// <returns>whether or not they are byte-for-byte equal</returns>
  49. public static unsafe bool UnsafeCompare(byte[] a1, byte[] a2)
  50. {
  51. if (a1 == a2) return true;
  52. if (a1 == null || a2 == null || a1.Length != a2.Length)
  53. return false;
  54. fixed (byte* p1 = a1, p2 = a2)
  55. {
  56. byte* x1 = p1, x2 = p2;
  57. int l = a1.Length;
  58. for (int i = 0; i < l / 8; i++, x1 += 8, x2 += 8)
  59. if (*((long*)x1) != *((long*)x2)) return false;
  60. if ((l & 4) != 0) { if (*((int*)x1) != *((int*)x2)) return false; x1 += 4; x2 += 4; }
  61. if ((l & 2) != 0) { if (*((short*)x1) != *((short*)x2)) return false; x1 += 2; x2 += 2; }
  62. if ((l & 1) != 0) if (*x1 != *x2) return false;
  63. return true;
  64. }
  65. }
  66. /// <summary>
  67. /// Gets a path relative to the provided folder.
  68. /// </summary>
  69. /// <param name="file">the file to relativize</param>
  70. /// <param name="folder">the source folder</param>
  71. /// <returns>a path to get from <paramref name="folder"/> to <paramref name="file"/></returns>
  72. public static string GetRelativePath(string file, string folder)
  73. {
  74. Uri pathUri = new Uri(file);
  75. // Folders must end in a slash
  76. if (!folder.EndsWith(Path.DirectorySeparatorChar.ToString()))
  77. {
  78. folder += Path.DirectorySeparatorChar;
  79. }
  80. Uri folderUri = new Uri(folder);
  81. return Uri.UnescapeDataString(folderUri.MakeRelativeUri(pathUri).ToString().Replace('/', Path.DirectorySeparatorChar));
  82. }
  83. /// <summary>
  84. /// Copies all files from <paramref name="source"/> to <paramref name="target"/>.
  85. /// </summary>
  86. /// <param name="source">the source directory</param>
  87. /// <param name="target">the destination directory</param>
  88. /// <param name="appendFileName">the filename of the file to append together</param>
  89. /// <param name="onCopyException">a delegate called when there is an error copying. Return true to keep going.</param>
  90. public static void CopyAll(DirectoryInfo source, DirectoryInfo target, string appendFileName = "",
  91. Func<Exception, FileInfo, bool> onCopyException = null)
  92. {
  93. if (source.FullName.ToLower() == target.FullName.ToLower())
  94. {
  95. return;
  96. }
  97. // Check if the target directory exists, if not, create it.
  98. if (Directory.Exists(target.FullName) == false)
  99. {
  100. Directory.CreateDirectory(target.FullName);
  101. }
  102. // Copy each file into it's new directory.
  103. foreach (FileInfo fi in source.GetFiles())
  104. {
  105. try
  106. {
  107. if (fi.Name == appendFileName)
  108. File.AppendAllLines(Path.Combine(target.ToString(), fi.Name), File.ReadAllLines(fi.FullName));
  109. else
  110. fi.CopyTo(Path.Combine(target.ToString(), fi.Name), true);
  111. }
  112. catch (Exception e)
  113. {
  114. var keepOn = onCopyException?.Invoke(e, fi);
  115. if (!keepOn.Unwrap())
  116. throw;
  117. }
  118. }
  119. // Copy each subdirectory using recursion.
  120. foreach (DirectoryInfo diSourceSubDir in source.GetDirectories())
  121. {
  122. DirectoryInfo nextTargetSubDir =
  123. target.CreateSubdirectory(diSourceSubDir.Name);
  124. CopyAll(diSourceSubDir, nextTargetSubDir, appendFileName, onCopyException);
  125. }
  126. }
  127. /// <summary>
  128. /// Whether you can safely use <see cref="DateTime.Now"/> without Mono throwing a fit.
  129. /// </summary>
  130. /// <value><see langword="true"/> if you can use <see cref="DateTime.Now"/> safely, <see langword="false"/> otherwise</value>
  131. public static bool CanUseDateTimeNowSafely { get; private set; } = true;
  132. private static bool DateTimeSafetyUnknown = true;
  133. private static ulong UnsafeAdvanceTicks = 1;
  134. /// <summary>
  135. /// Gets the current <see cref="DateTime"/> if supported, otherwise, if Mono would throw a fit,
  136. /// returns <see cref="DateTime.MinValue"/> plus some value, such that each time it is called
  137. /// the value will be greater than the previous result. Not suitable for timing.
  138. /// </summary>
  139. /// <returns>the current <see cref="DateTime"/> if supported, otherwise some indeterminant increasing value.</returns>
  140. public static DateTime CurrentTime()
  141. {
  142. if (DateTimeSafetyUnknown)
  143. {
  144. DateTime time = DateTime.MinValue;
  145. try
  146. {
  147. time = DateTime.Now;
  148. }
  149. catch (TimeZoneNotFoundException)
  150. { // Mono did a fucky wucky and we need to avoid this call
  151. CanUseDateTimeNowSafely = false;
  152. }
  153. DateTimeSafetyUnknown = false;
  154. return time;
  155. }
  156. else
  157. {
  158. if (CanUseDateTimeNowSafely) return DateTime.Now;
  159. else return DateTime.MinValue.AddTicks((long)UnsafeAdvanceTicks++); // return MinValue as a fallback
  160. }
  161. }
  162. /// <summary>
  163. /// Compares a pair of <see cref="SemVer.Version"/>s ignoring both the prerelease and build fields.
  164. /// </summary>
  165. /// <param name="l">the left value</param>
  166. /// <param name="r">the right value</param>
  167. /// <returns>-1 if l is less than r, 0 if they are equal in the numeric portion, or 1 if l is greater than r</returns>
  168. public static int VersionCompareNoPrerelease(SemVer.Version l, SemVer.Version r)
  169. {
  170. var cmpVal = l.Major - r.Major;
  171. if (cmpVal != 0) return cmpVal;
  172. cmpVal = l.Minor - r.Minor;
  173. if (cmpVal != 0) return cmpVal;
  174. cmpVal = l.Patch - r.Patch;
  175. return cmpVal;
  176. }
  177. }
  178. }