123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472 |
- using System;
- using System.Collections.Generic;
- using System.Text;
- using System.Reflection;
- using System.Threading;
- using System.IO;
- using System.Diagnostics;
- using System.Security.Cryptography;
- namespace Beefy
- {
- public static class Utils
- {
- static Random mRandom = new Random() ~ delete _;
- [StdCall, CLink]
- static extern int32 BF_TickCount();
- [StdCall, CLink]
- static extern int32 BF_TickCountMicroFast();
- public static float Deg2Rad = Math.PI_f / 180.0f;
-
- public static int32 Rand()
- {
- return mRandom.NextI32();
- }
- public static float RandFloat()
- {
- return (Rand() & 0xFFFFFF) / (float)0xFFFFFF;
- }
- public static float Interpolate(float left, float right, float pct)
- {
- return left + (right - left) * pct;
- }
- public static float Clamp(float val, float min, float max)
- {
- return Math.Max(min, Math.Min(max, val));
- }
- public static float Lerp(float val1, float val2, float pct)
- {
- return val1 + (val2 - val1) * pct;
- }
- public static float EaseInAndOut(float pct)
- {
- return ((-Math.Cos(pct * Math.PI_f) + 1.0f) / 2.0f);
- }
- public static float Distance(float dX, float dY)
- {
- return Math.Sqrt(dX * dX + dY * dY);
- }
- public static char8 CtrlKeyChar(char32 theChar)
- {
- char8 aChar = (char8)(theChar + (int)'A' - (char8)1);
- if (aChar < (char8)0)
- return (char8)0;
- return aChar;
- }
- public static uint32 GetTickCount()
- {
- return (uint32)BF_TickCount();
- }
- public static uint64 GetTickCountMicro()
- {
- return (uint32)BF_TickCountMicroFast();
- }
- public static Object DefaultConstruct(Type theType)
- {
- ThrowUnimplemented();
- /*ConstructorInfo constructor = theType.GetConstructors()[0];
- ParameterInfo[] paramInfos = constructor.GetParameters();
- object[] aParams = new object[paramInfos.Length];
- for (int paramIdx = 0; paramIdx < aParams.Length; paramIdx++)
- aParams[paramIdx] = paramInfos[paramIdx].DefaultValue;
- object newObject = constructor.Invoke(aParams);
- return newObject;*/
- }
- /*public static int StrToInt(string theString)
- {
- if (theString.StartsWith("0X", StringComparison.OrdinalIgnoreCase))
- return Convert.ToInt32(theString.Substring(2), 16);
- return Convert.ToInt32(theString);
- }
- // WaitForEvent differs from theEvent.WaitOne in that it doesn't pump the Windows
- // message loop under STAThread
- public static bool WaitForEvent(EventWaitHandle theEvent, int timeMS)
- {
- return WaitForSingleObject(theEvent.SafeWaitHandle, timeMS) == 0;
- }*/
-
- public static void GetDirWithSlash(String dir)
- {
- if (dir.IsEmpty)
- return;
- char8 endChar = dir[dir.Length - 1];
- if ((endChar != Path.DirectorySeparatorChar) && (endChar != Path.AltDirectorySeparatorChar))
- dir.Append(Path.DirectorySeparatorChar);
- }
- public static Result<void> DelTree(String path, Predicate<String> fileFilter = null)
- {
- if (path.Length <= 2)
- return .Err;
- if ((path[0] != '/') && (path[0] != '\\'))
- {
- if (path[1] == ':')
- {
- if (path.Length < 3)
- return .Err;
- }
- else
- return .Err;
- }
- for (var fileEntry in Directory.EnumerateDirectories(path))
- {
- let fileName = scope String();
- fileEntry.GetFilePath(fileName);
- Try!(DelTree(fileName, fileFilter));
- }
- for (var fileEntry in Directory.EnumerateFiles(path))
- {
- let fileName = scope String();
- fileEntry.GetFilePath(fileName);
- if (fileFilter != null)
- if (!fileFilter(fileName))
- continue;
- Try!(File.SetAttributes(fileName, FileAttributes.Archive));
- Try!(File.Delete(fileName));
- }
- // Allow failure for the directory, this can often be locked for various reasons
- // but we only consider a file failure to be an "actual" failure
- Directory.Delete(path).IgnoreError();
- return .Ok;
- }
- public static Result<void, FileError> LoadTextFile(String fileName, String outBuffer, bool autoRetry = true, delegate void() onPreFilter = null)
- {
- FileStream sr = scope .();
-
- // Retry for a while if the other side is still writing out the file
- for (int i = 0; i < 100; i++)
- {
- if (sr.Open(fileName, .Read, .Read) case .Err(let fileOpenErr))
- {
- bool retry = false;
- if (autoRetry)
- {
- if (fileOpenErr == .SharingViolation)
- retry = true;
- }
- if (!retry)
- return .Err(.FileOpenError(fileOpenErr));
- }
- else
- break;
- Thread.Sleep(20);
- }
- int fileLen = (.)sr.Length;
- if (sr.TryRead(.((.)outBuffer.PrepareBuffer(fileLen), fileLen)) case .Err(let readErr))
- return .Err(.FileReadError(readErr));
- if (onPreFilter != null)
- onPreFilter();
- int startLen = Math.Min(fileLen, 4);
- Span<uint8> bomSpan = .((.)outBuffer.Ptr, startLen);
- var encoding = Encoding.DetectEncoding(bomSpan, var bomSize);
- if (bomSize > 0)
- {
- if (encoding == .UTF8WithBOM)
- {
- outBuffer.Remove(0, bomSize);
- }
- else
- {
- String srcBuffer = scope .();
- outBuffer.MoveTo(srcBuffer);
- Span<uint8> inSpan = .((.)srcBuffer.Ptr, srcBuffer.Length);
- inSpan.RemoveFromStart(bomSize);
- encoding.DecodeToUTF8(inSpan, outBuffer).IgnoreError();
- }
- }
- /*if (hashPtr != null)
- *hashPtr = MD5.Hash(Span<uint8>((uint8*)outBuffer.Ptr, outBuffer.Length));*/
- bool isAscii = false;
- int outIdx = 0;
- for (int32 i = 0; i < outBuffer.Length; i++)
- {
- char8 c = outBuffer[i];
- if (c >= '\x80')
- {
- switch (UTF8.TryDecode(outBuffer.Ptr + i, outBuffer.Length - i))
- {
- case .Ok((?, let len)):
- if (len > 1)
- {
- for (int cnt < len)
- {
- char8 cPart = outBuffer[i++];
- outBuffer[outIdx++] = cPart;
- }
- i--;
- continue;
- }
- case .Err: isAscii = true;
- }
- }
- if (c != '\r')
- {
- if (outIdx == i)
- {
- outIdx++;
- continue;
- }
- outBuffer[outIdx++] = c;
- }
- }
- outBuffer.RemoveToEnd(outIdx);
- if (isAscii)
- {
- String prevBuffer = scope String();
- outBuffer.MoveTo(prevBuffer);
- for (var c in prevBuffer.RawChars)
- {
- outBuffer.Append((char32)c, 1);
- }
- }
- return .Ok;
- }
- public static bool FileTextEquals(String textA, String textB)
- {
- int32 posA = 0;
- int32 posB = 0;
- while (true)
- {
- char8 char8A = (char8)0;
- char8 char8B = (char8)0;
- while (posA < textA.Length)
- {
- char8A = textA[posA++];
- if (char8A != '\r')
- break;
- char8A = (char8)0;
- }
- while (posB < textB.Length)
- {
- char8B = textB[posB++];
- if (char8B != '\r')
- break;
- char8B = (char8)0;
- }
- if ((char8A == (char8)0) && (char8B == (char8)0))
- return true;
- if (char8A != char8B)
- return false;
- }
- }
- public static Result<void> WriteTextFile(StringView path, StringView text)
- {
- var stream = scope FileStream();
- if (stream.Create(path) case .Err)
- {
- return .Err;
- }
- if (stream.WriteStrUnsized(text) case .Err)
- return .Err;
-
- return .Ok;
- }
- public static int LevenshteinDistance(String s, String t)
- {
- int n = s.Length;
- int m = t.Length;
- int32[,] d = new int32[n + 1, m + 1];
- defer delete d;
- if (n == 0)
- {
- return m;
- }
- if (m == 0)
- {
- return n;
- }
- for (int32 i = 0; i <= n; d[i, 0] = i++)
- {}
- for (int32 j = 0; j <= m; d[0, j] = j++)
- {}
- for (int32 i = 1; i <= n; i++)
- {
- for (int32 j = 1; j <= m; j++)
- {
- int32 cost = (t[j - 1] == s[i - 1]) ? 0 : 1;
- d[i, j] = Math.Min(
- Math.Min(d[i - 1, j] + 1, d[i, j - 1] + 1),
- d[i - 1, j - 1] + cost);
- }
- }
- return d[n, m];
- }
- /*public static List<TSource> ToSortedList<TSource>(this IEnumerable<TSource> source)
- {
- var list = source.ToList();
- list.Sort();
- return list;
- }*/
- public static int64 DecodeInt64(ref uint8* ptr)
- {
- int64 value = 0;
- int32 shift = 0;
- int64 curByte;
- repeat
- {
- curByte = *(ptr++);
- value |= ((curByte & 0x7f) << shift);
- shift += 7;
-
- } while (curByte >= 128);
- // Sign extend negative numbers.
- if (((curByte & 0x40) != 0) && (shift < 64))
- value |= -1 << shift;
- return value;
- }
- public static int32 DecodeInt(uint8[] buf, ref int idx)
- {
- int32 value = 0;
- int32 Shift = 0;
- int32 curByte;
- repeat
- {
- curByte = buf[idx++];
- value |= ((curByte & 0x7f) << Shift);
- Shift += 7;
- } while (curByte >= 128);
- // Sign extend negative numbers.
- if ((curByte & 0x40) != 0)
- value |= -1 << Shift;
- return value;
- }
- public static void EncodeInt(uint8[] buf, ref int idx, int value)
- {
- int curValue = value;
- bool hasMore;
- repeat
- {
- uint8 curByte = (uint8)(curValue & 0x7f);
- curValue >>= 7;
- hasMore = !((((curValue == 0) && ((curByte & 0x40) == 0)) ||
- ((curValue == -1) && ((curByte & 0x40) != 0))));
- if (hasMore)
- curByte |= 0x80;
- buf[idx++] = curByte;
- }
- while (hasMore);
- }
- public static bool Contains<T>(IEnumerator<T> itr, T value)
- {
- for (var check in itr)
- if (check == value)
- return true;
- return false;
- }
- public static void QuoteString(String str, String strOut)
- {
- strOut.Append('"');
- for (int i < str.Length)
- {
- char8 c = str[i];
- strOut.Append(c);
- }
- strOut.Append('"');
- }
- public static void ParseSpaceSep(String str, ref int idx, String subStr)
- {
- while (idx < str.Length)
- {
- char8 c = str[idx];
- if (c != ' ')
- break;
- idx++;
- }
- if (idx >= str.Length)
- return;
- // Quoted
- if (str[idx] == '"')
- {
- idx++;
- while (idx < str.Length)
- {
- char8 c = str[idx++];
- if (c == '"')
- break;
- subStr.Append(c);
- }
- return;
- }
- // Unquoted
- while (idx < str.Length)
- {
- char8 c = str[idx++];
- if (c == ' ')
- break;
- subStr.Append(c);
- }
- }
- public static void SnapScale(ref float val, float scale)
- {
- val *= scale;
- float frac = val - (int)val;
- if ((frac <= 0.001f) || (frac >= 0.999f))
- val = (float)Math.Round(val);
- }
- public static void RoundScale(ref float val, float scale)
- {
- val = (float)Math.Round(val * scale);
- }
- }
- }
|