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.

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