Keine Beschreibung
Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

SafeStringArrayHelper.cs 2.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. namespace Unity.Burst
  5. {
  6. #if BURST_COMPILER_SHARED
  7. public static class SafeStringArrayHelper
  8. #else
  9. internal static class SafeStringArrayHelper
  10. #endif
  11. {
  12. // Methods to help when needing to serialise arrays of strings safely
  13. public static string SerialiseStringArraySafe(string[] array)
  14. {
  15. var s = new StringBuilder();
  16. foreach (var entry in array)
  17. {
  18. s.Append($"{Encoding.UTF8.GetByteCount(entry)}]");
  19. s.Append(entry);
  20. }
  21. return s.ToString();
  22. }
  23. public static string[] DeserialiseStringArraySafe(string input)
  24. {
  25. // Safer method of serialisation (len]path) e.g. "5]frank8]c:\\billy" ( new [] {"frank","c:\\billy"} )
  26. // Since the len part of `len]path` is specified in bytes we'll be working on a byte array instead
  27. // of a string, because functions like Substring expects char offsets and number of chars.
  28. var bytes = Encoding.UTF8.GetBytes(input);
  29. var listFolders = new List<string>();
  30. var index = 0;
  31. var length = bytes.Length;
  32. while (index < length)
  33. {
  34. int len = 0;
  35. // Read the decimal encoded length, terminated by an ']'
  36. while (true)
  37. {
  38. if (index >= length)
  39. {
  40. throw new FormatException($"Invalid input `{input}`: reached end while reading length");
  41. }
  42. var d = bytes[index];
  43. if (d == ']')
  44. {
  45. index++;
  46. break;
  47. }
  48. if (d < '0' || d > '9')
  49. {
  50. throw new FormatException(
  51. $"Invalid input `{input}` at {index}: Got non-digit character while reading length");
  52. }
  53. len = len * 10 + (d - '0');
  54. index++;
  55. }
  56. listFolders.Add(Encoding.UTF8.GetString(bytes, index, len));
  57. index += len;
  58. }
  59. return listFolders.ToArray();
  60. }
  61. }
  62. }