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.

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