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