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.

243 lines
10 KiB

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