Utils.bf 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. using System.Reflection;
  5. using System.Threading;
  6. using System.IO;
  7. using System.Diagnostics;
  8. using System.Security.Cryptography;
  9. namespace Beefy
  10. {
  11. public static class Utils
  12. {
  13. static Random mRandom = new Random() ~ delete _;
  14. [StdCall, CLink]
  15. static extern int32 BF_TickCount();
  16. [StdCall, CLink]
  17. static extern int32 BF_TickCountMicroFast();
  18. public static float Deg2Rad = Math.PI_f / 180.0f;
  19. public static int32 Rand()
  20. {
  21. return mRandom.NextI32();
  22. }
  23. public static float RandFloat()
  24. {
  25. return (Rand() & 0xFFFFFF) / (float)0xFFFFFF;
  26. }
  27. public static float Interpolate(float left, float right, float pct)
  28. {
  29. return left + (right - left) * pct;
  30. }
  31. public static float Clamp(float val, float min, float max)
  32. {
  33. return Math.Max(min, Math.Min(max, val));
  34. }
  35. public static float Lerp(float val1, float val2, float pct)
  36. {
  37. return val1 + (val2 - val1) * pct;
  38. }
  39. public static float EaseInAndOut(float pct)
  40. {
  41. return ((-Math.Cos(pct * Math.PI_f) + 1.0f) / 2.0f);
  42. }
  43. public static float Distance(float dX, float dY)
  44. {
  45. return Math.Sqrt(dX * dX + dY * dY);
  46. }
  47. public static char8 CtrlKeyChar(char32 theChar)
  48. {
  49. char8 aChar = (char8)(theChar + (int)'A' - (char8)1);
  50. if (aChar < (char8)0)
  51. return (char8)0;
  52. return aChar;
  53. }
  54. public static uint32 GetTickCount()
  55. {
  56. return (uint32)BF_TickCount();
  57. }
  58. public static uint64 GetTickCountMicro()
  59. {
  60. return (uint32)BF_TickCountMicroFast();
  61. }
  62. public static Object DefaultConstruct(Type theType)
  63. {
  64. ThrowUnimplemented();
  65. /*ConstructorInfo constructor = theType.GetConstructors()[0];
  66. ParameterInfo[] paramInfos = constructor.GetParameters();
  67. object[] aParams = new object[paramInfos.Length];
  68. for (int paramIdx = 0; paramIdx < aParams.Length; paramIdx++)
  69. aParams[paramIdx] = paramInfos[paramIdx].DefaultValue;
  70. object newObject = constructor.Invoke(aParams);
  71. return newObject;*/
  72. }
  73. /*public static int StrToInt(string theString)
  74. {
  75. if (theString.StartsWith("0X", StringComparison.OrdinalIgnoreCase))
  76. return Convert.ToInt32(theString.Substring(2), 16);
  77. return Convert.ToInt32(theString);
  78. }
  79. // WaitForEvent differs from theEvent.WaitOne in that it doesn't pump the Windows
  80. // message loop under STAThread
  81. public static bool WaitForEvent(EventWaitHandle theEvent, int timeMS)
  82. {
  83. return WaitForSingleObject(theEvent.SafeWaitHandle, timeMS) == 0;
  84. }*/
  85. public static void GetDirWithSlash(String dir)
  86. {
  87. if (dir.IsEmpty)
  88. return;
  89. char8 endChar = dir[dir.Length - 1];
  90. if ((endChar != Path.DirectorySeparatorChar) && (endChar != Path.AltDirectorySeparatorChar))
  91. dir.Append(Path.DirectorySeparatorChar);
  92. }
  93. public static Result<void> DelTree(String path, Predicate<String> fileFilter = null)
  94. {
  95. if (path.Length <= 2)
  96. return .Err;
  97. if ((path[0] != '/') && (path[0] != '\\'))
  98. {
  99. if (path[1] == ':')
  100. {
  101. if (path.Length < 3)
  102. return .Err;
  103. }
  104. else
  105. return .Err;
  106. }
  107. for (var fileEntry in Directory.EnumerateDirectories(path))
  108. {
  109. let fileName = scope String();
  110. fileEntry.GetFilePath(fileName);
  111. Try!(DelTree(fileName, fileFilter));
  112. }
  113. for (var fileEntry in Directory.EnumerateFiles(path))
  114. {
  115. let fileName = scope String();
  116. fileEntry.GetFilePath(fileName);
  117. if (fileFilter != null)
  118. if (!fileFilter(fileName))
  119. continue;
  120. Try!(File.SetAttributes(fileName, FileAttributes.Archive));
  121. Try!(File.Delete(fileName));
  122. }
  123. // Allow failure for the directory, this can often be locked for various reasons
  124. // but we only consider a file failure to be an "actual" failure
  125. Directory.Delete(path).IgnoreError();
  126. return .Ok;
  127. }
  128. public static Result<void, FileError> LoadTextFile(String fileName, String outBuffer, bool autoRetry = true, delegate void() onPreFilter = null)
  129. {
  130. FileStream sr = scope .();
  131. // Retry for a while if the other side is still writing out the file
  132. for (int i = 0; i < 100; i++)
  133. {
  134. if (sr.Open(fileName, .Read, .Read) case .Err(let fileOpenErr))
  135. {
  136. bool retry = false;
  137. if (autoRetry)
  138. {
  139. if (fileOpenErr == .SharingViolation)
  140. retry = true;
  141. }
  142. if (!retry)
  143. return .Err(.FileOpenError(fileOpenErr));
  144. }
  145. else
  146. break;
  147. Thread.Sleep(20);
  148. }
  149. int fileLen = (.)sr.Length;
  150. if (sr.TryRead(.((.)outBuffer.PrepareBuffer(fileLen), fileLen)) case .Err(let readErr))
  151. return .Err(.FileReadError(readErr));
  152. if (onPreFilter != null)
  153. onPreFilter();
  154. int startLen = Math.Min(fileLen, 4);
  155. Span<uint8> bomSpan = .((.)outBuffer.Ptr, startLen);
  156. var encoding = Encoding.DetectEncoding(bomSpan, var bomSize);
  157. if (bomSize > 0)
  158. {
  159. if (encoding == .UTF8WithBOM)
  160. {
  161. outBuffer.Remove(0, bomSize);
  162. }
  163. else
  164. {
  165. String srcBuffer = scope .();
  166. outBuffer.MoveTo(srcBuffer);
  167. Span<uint8> inSpan = .((.)srcBuffer.Ptr, srcBuffer.Length);
  168. inSpan.RemoveFromStart(bomSize);
  169. encoding.DecodeToUTF8(inSpan, outBuffer).IgnoreError();
  170. }
  171. }
  172. /*if (hashPtr != null)
  173. *hashPtr = MD5.Hash(Span<uint8>((uint8*)outBuffer.Ptr, outBuffer.Length));*/
  174. bool isAscii = false;
  175. int outIdx = 0;
  176. for (int32 i = 0; i < outBuffer.Length; i++)
  177. {
  178. char8 c = outBuffer[i];
  179. if (c >= '\x80')
  180. {
  181. switch (UTF8.TryDecode(outBuffer.Ptr + i, outBuffer.Length - i))
  182. {
  183. case .Ok((?, let len)):
  184. if (len > 1)
  185. {
  186. for (int cnt < len)
  187. {
  188. char8 cPart = outBuffer[i++];
  189. outBuffer[outIdx++] = cPart;
  190. }
  191. i--;
  192. continue;
  193. }
  194. case .Err: isAscii = true;
  195. }
  196. }
  197. if (c != '\r')
  198. {
  199. if (outIdx == i)
  200. {
  201. outIdx++;
  202. continue;
  203. }
  204. outBuffer[outIdx++] = c;
  205. }
  206. }
  207. outBuffer.RemoveToEnd(outIdx);
  208. if (isAscii)
  209. {
  210. String prevBuffer = scope String();
  211. outBuffer.MoveTo(prevBuffer);
  212. for (var c in prevBuffer.RawChars)
  213. {
  214. outBuffer.Append((char32)c, 1);
  215. }
  216. }
  217. return .Ok;
  218. }
  219. public static bool FileTextEquals(String textA, String textB)
  220. {
  221. int32 posA = 0;
  222. int32 posB = 0;
  223. while (true)
  224. {
  225. char8 char8A = (char8)0;
  226. char8 char8B = (char8)0;
  227. while (posA < textA.Length)
  228. {
  229. char8A = textA[posA++];
  230. if (char8A != '\r')
  231. break;
  232. char8A = (char8)0;
  233. }
  234. while (posB < textB.Length)
  235. {
  236. char8B = textB[posB++];
  237. if (char8B != '\r')
  238. break;
  239. char8B = (char8)0;
  240. }
  241. if ((char8A == (char8)0) && (char8B == (char8)0))
  242. return true;
  243. if (char8A != char8B)
  244. return false;
  245. }
  246. }
  247. public static Result<void> WriteTextFile(StringView path, StringView text)
  248. {
  249. var stream = scope FileStream();
  250. if (stream.Create(path) case .Err)
  251. {
  252. return .Err;
  253. }
  254. if (stream.WriteStrUnsized(text) case .Err)
  255. return .Err;
  256. return .Ok;
  257. }
  258. public static int LevenshteinDistance(String s, String t)
  259. {
  260. int n = s.Length;
  261. int m = t.Length;
  262. int32[,] d = new int32[n + 1, m + 1];
  263. defer delete d;
  264. if (n == 0)
  265. {
  266. return m;
  267. }
  268. if (m == 0)
  269. {
  270. return n;
  271. }
  272. for (int32 i = 0; i <= n; d[i, 0] = i++)
  273. {}
  274. for (int32 j = 0; j <= m; d[0, j] = j++)
  275. {}
  276. for (int32 i = 1; i <= n; i++)
  277. {
  278. for (int32 j = 1; j <= m; j++)
  279. {
  280. int32 cost = (t[j - 1] == s[i - 1]) ? 0 : 1;
  281. d[i, j] = Math.Min(
  282. Math.Min(d[i - 1, j] + 1, d[i, j - 1] + 1),
  283. d[i - 1, j - 1] + cost);
  284. }
  285. }
  286. return d[n, m];
  287. }
  288. /*public static List<TSource> ToSortedList<TSource>(this IEnumerable<TSource> source)
  289. {
  290. var list = source.ToList();
  291. list.Sort();
  292. return list;
  293. }*/
  294. public static int64 DecodeInt64(ref uint8* ptr)
  295. {
  296. int64 value = 0;
  297. int32 shift = 0;
  298. int64 curByte;
  299. repeat
  300. {
  301. curByte = *(ptr++);
  302. value |= ((curByte & 0x7f) << shift);
  303. shift += 7;
  304. } while (curByte >= 128);
  305. // Sign extend negative numbers.
  306. if (((curByte & 0x40) != 0) && (shift < 64))
  307. value |= -1 << shift;
  308. return value;
  309. }
  310. public static int32 DecodeInt(uint8[] buf, ref int idx)
  311. {
  312. int32 value = 0;
  313. int32 Shift = 0;
  314. int32 curByte;
  315. repeat
  316. {
  317. curByte = buf[idx++];
  318. value |= ((curByte & 0x7f) << Shift);
  319. Shift += 7;
  320. } while (curByte >= 128);
  321. // Sign extend negative numbers.
  322. if ((curByte & 0x40) != 0)
  323. value |= -1 << Shift;
  324. return value;
  325. }
  326. public static void EncodeInt(uint8[] buf, ref int idx, int value)
  327. {
  328. int curValue = value;
  329. bool hasMore;
  330. repeat
  331. {
  332. uint8 curByte = (uint8)(curValue & 0x7f);
  333. curValue >>= 7;
  334. hasMore = !((((curValue == 0) && ((curByte & 0x40) == 0)) ||
  335. ((curValue == -1) && ((curByte & 0x40) != 0))));
  336. if (hasMore)
  337. curByte |= 0x80;
  338. buf[idx++] = curByte;
  339. }
  340. while (hasMore);
  341. }
  342. public static bool Contains<T>(IEnumerator<T> itr, T value)
  343. {
  344. for (var check in itr)
  345. if (check == value)
  346. return true;
  347. return false;
  348. }
  349. public static void QuoteString(String str, String strOut)
  350. {
  351. strOut.Append('"');
  352. for (int i < str.Length)
  353. {
  354. char8 c = str[i];
  355. strOut.Append(c);
  356. }
  357. strOut.Append('"');
  358. }
  359. public static void ParseSpaceSep(String str, ref int idx, String subStr)
  360. {
  361. while (idx < str.Length)
  362. {
  363. char8 c = str[idx];
  364. if (c != ' ')
  365. break;
  366. idx++;
  367. }
  368. if (idx >= str.Length)
  369. return;
  370. // Quoted
  371. if (str[idx] == '"')
  372. {
  373. idx++;
  374. while (idx < str.Length)
  375. {
  376. char8 c = str[idx++];
  377. if (c == '"')
  378. break;
  379. subStr.Append(c);
  380. }
  381. return;
  382. }
  383. // Unquoted
  384. while (idx < str.Length)
  385. {
  386. char8 c = str[idx++];
  387. if (c == ' ')
  388. break;
  389. subStr.Append(c);
  390. }
  391. }
  392. public static void SnapScale(ref float val, float scale)
  393. {
  394. val *= scale;
  395. float frac = val - (int)val;
  396. if ((frac <= 0.001f) || (frac >= 0.999f))
  397. val = (float)Math.Round(val);
  398. }
  399. public static void RoundScale(ref float val, float scale)
  400. {
  401. val = (float)Math.Round(val * scale);
  402. }
  403. }
  404. }