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.

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