暫無描述
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.

Deprecated.cs 83KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.Diagnostics;
  5. using System.Runtime.InteropServices;
  6. using System.Threading;
  7. using Unity.Jobs;
  8. using Unity.Mathematics;
  9. using UnityEngine.Assertions;
  10. using Unity.Burst;
  11. using UnityEngine;
  12. using static Unity.Baselib.LowLevel.Binding;
  13. #pragma warning disable 618 // disable obsolete warnings
  14. namespace Unity.Collections.LowLevel.Unsafe
  15. {
  16. /// <summary>
  17. /// An unmanaged, untyped, resizable list, without any thread safety check features.
  18. /// </summary>
  19. [DebuggerDisplay("Length = {Length}, Capacity = {Capacity}, IsCreated = {IsCreated}, IsEmpty = {IsEmpty}")]
  20. [StructLayout(LayoutKind.Sequential)]
  21. [Obsolete("Untyped UnsafeList is deprecated, please use UnsafeList<T> instead. (RemovedAfter 2021-05-18)", false)]
  22. public unsafe struct UnsafeList
  23. : INativeDisposable
  24. {
  25. /// <summary>
  26. /// </summary>
  27. [NativeDisableUnsafePtrRestriction]
  28. public void* Ptr;
  29. /// <summary>
  30. /// </summary>
  31. public int Length;
  32. public readonly int unused;
  33. /// <summary>
  34. /// </summary>
  35. public int Capacity;
  36. /// <summary>
  37. /// </summary>
  38. public AllocatorManager.AllocatorHandle Allocator;
  39. /// <summary>
  40. /// Constructs a new container with type of memory allocation.
  41. /// </summary>
  42. /// <param name="allocator">A member of the
  43. /// [Unity.Collections.Allocator](https://docs.unity3d.com/ScriptReference/Unity.Collections.Allocator.html) enumeration.</param>
  44. /// <remarks>The list initially has a capacity of one. To avoid reallocating memory for the list, specify
  45. /// sufficient capacity up front.</remarks>
  46. public UnsafeList(Allocator allocator) : this()
  47. {
  48. Ptr = null;
  49. Length = 0;
  50. Capacity = 0;
  51. Allocator = allocator;
  52. }
  53. /// <summary>
  54. /// Constructs container as view into memory.
  55. /// </summary>
  56. /// <param name="ptr">Pointer to data.</param>
  57. /// <param name="length">Lenght of data in bytes.</param>
  58. public UnsafeList(void* ptr, int length) : this()
  59. {
  60. Ptr = ptr;
  61. Length = length;
  62. Capacity = length;
  63. Allocator = Collections.Allocator.None;
  64. }
  65. internal void Initialize<U>(int sizeOf, int alignOf, int initialCapacity, ref U allocator, NativeArrayOptions options = NativeArrayOptions.UninitializedMemory) where U : unmanaged, AllocatorManager.IAllocator
  66. {
  67. Allocator = allocator.Handle;
  68. Ptr = null;
  69. Length = 0;
  70. Capacity = 0;
  71. if (initialCapacity != 0)
  72. {
  73. SetCapacity(ref allocator, sizeOf, alignOf, initialCapacity);
  74. }
  75. if (options == NativeArrayOptions.ClearMemory
  76. && Ptr != null)
  77. {
  78. UnsafeUtility.MemClear(Ptr, Capacity * sizeOf);
  79. }
  80. }
  81. internal static UnsafeList New<U>(int sizeOf, int alignOf, int initialCapacity, ref U allocator, NativeArrayOptions options = NativeArrayOptions.UninitializedMemory) where U : unmanaged, AllocatorManager.IAllocator
  82. {
  83. var temp = new UnsafeList();
  84. temp.Initialize(sizeOf, alignOf, initialCapacity, ref allocator, options);
  85. return temp;
  86. }
  87. /// <summary>
  88. /// Constructs a new container with the specified initial capacity and type of memory allocation.
  89. /// </summary>
  90. /// <param name="sizeOf">Size of element.</param>
  91. /// <param name="alignOf">Alignment of element.</param>
  92. /// <param name="initialCapacity">The initial capacity of the list. If the list grows larger than its capacity,
  93. /// the internal array is copied to a new, larger array.</param>
  94. /// <param name="allocator">A member of the
  95. /// [Unity.Collections.Allocator](https://docs.unity3d.com/ScriptReference/Unity.Collections.Allocator.html) enumeration.</param>
  96. /// <param name="options">Memory should be cleared on allocation or left uninitialized.</param>
  97. public UnsafeList(int sizeOf, int alignOf, int initialCapacity, AllocatorManager.AllocatorHandle allocator, NativeArrayOptions options = NativeArrayOptions.UninitializedMemory) : this()
  98. {
  99. this = default;
  100. Initialize(sizeOf, alignOf, initialCapacity, ref allocator, options);
  101. }
  102. /// <summary>
  103. /// Constructs a new container with the specified initial capacity and type of memory allocation.
  104. /// </summary>
  105. /// <param name="sizeOf">Size of element.</param>
  106. /// <param name="alignOf">Alignment of element.</param>
  107. /// <param name="initialCapacity">The initial capacity of the list. If the list grows larger than its capacity,
  108. /// the internal array is copied to a new, larger array.</param>
  109. /// <param name="allocator">A member of the
  110. /// [Unity.Collections.Allocator](https://docs.unity3d.com/ScriptReference/Unity.Collections.Allocator.html) enumeration.</param>
  111. /// <param name="options">Memory should be cleared on allocation or left uninitialized.</param>
  112. public UnsafeList(int sizeOf, int alignOf, int initialCapacity, Allocator allocator, NativeArrayOptions options = NativeArrayOptions.UninitializedMemory) : this()
  113. {
  114. Allocator = allocator;
  115. Ptr = null;
  116. Length = 0;
  117. Capacity = 0;
  118. if (initialCapacity != 0)
  119. {
  120. SetCapacity(sizeOf, alignOf, initialCapacity);
  121. }
  122. if (options == NativeArrayOptions.ClearMemory
  123. && Ptr != null)
  124. {
  125. UnsafeUtility.MemClear(Ptr, Capacity * sizeOf);
  126. }
  127. }
  128. /// <summary>
  129. /// Creates a new container with the specified initial capacity and type of memory allocation.
  130. /// </summary>
  131. /// <param name="sizeOf">Size of element.</param>
  132. /// <param name="alignOf">Alignment of element.</param>
  133. /// <param name="initialCapacity">The initial capacity of the list. If the list grows larger than its capacity,
  134. /// the internal array is copied to a new, larger array.</param>
  135. /// <param name="allocator">A member of the
  136. /// [Unity.Collections.Allocator](https://docs.unity3d.com/ScriptReference/Unity.Collections.Allocator.html) enumeration.</param>
  137. /// <param name="options">Memory should be cleared on allocation or left uninitialized.</param>
  138. /// <returns>New initialized container.</returns>
  139. public static UnsafeList* Create(int sizeOf, int alignOf, int initialCapacity, Allocator allocator, NativeArrayOptions options = NativeArrayOptions.UninitializedMemory)
  140. {
  141. var handle = (AllocatorManager.AllocatorHandle)allocator;
  142. UnsafeList* listData = AllocatorManager.Allocate<UnsafeList>(handle);
  143. UnsafeUtility.MemClear(listData, UnsafeUtility.SizeOf<UnsafeList>());
  144. listData->Allocator = allocator;
  145. if (initialCapacity != 0)
  146. {
  147. listData->SetCapacity(sizeOf, alignOf, initialCapacity);
  148. }
  149. if (options == NativeArrayOptions.ClearMemory
  150. && listData->Ptr != null)
  151. {
  152. UnsafeUtility.MemClear(listData->Ptr, listData->Capacity * sizeOf);
  153. }
  154. return listData;
  155. }
  156. internal static UnsafeList* Create<U>(int sizeOf, int alignOf, int initialCapacity, ref U allocator, NativeArrayOptions options = NativeArrayOptions.UninitializedMemory) where U : unmanaged, AllocatorManager.IAllocator
  157. {
  158. UnsafeList* listData = allocator.Allocate(default(UnsafeList), 1);
  159. UnsafeUtility.MemClear(listData, UnsafeUtility.SizeOf<UnsafeList>());
  160. listData->Allocator = allocator.Handle;
  161. if (initialCapacity != 0)
  162. {
  163. listData->SetCapacity(ref allocator, sizeOf, alignOf, initialCapacity);
  164. }
  165. if (options == NativeArrayOptions.ClearMemory
  166. && listData->Ptr != null)
  167. {
  168. UnsafeUtility.MemClear(listData->Ptr, listData->Capacity * sizeOf);
  169. }
  170. return listData;
  171. }
  172. internal static void Destroy<U>(UnsafeList* listData, ref U allocator, int sizeOf, int alignOf) where U : unmanaged, AllocatorManager.IAllocator
  173. {
  174. CheckNull(listData);
  175. listData->Dispose(ref allocator, sizeOf, alignOf);
  176. allocator.Free(listData, UnsafeUtility.SizeOf<UnsafeList>(), UnsafeUtility.AlignOf<UnsafeList>(), 1);
  177. }
  178. /// <summary>
  179. /// Destroys container.
  180. /// </summary>
  181. /// <param name="listData">Container to destroy.</param>
  182. public static void Destroy(UnsafeList* listData)
  183. {
  184. CheckNull(listData);
  185. var allocator = listData->Allocator;
  186. listData->Dispose();
  187. AllocatorManager.Free(allocator, listData);
  188. }
  189. /// <summary>
  190. /// Reports whether container is empty.
  191. /// </summary>
  192. /// <value>True if this string has no characters or if the container has not been constructed.</value>
  193. public bool IsEmpty => !IsCreated || Length == 0;
  194. /// <summary>
  195. /// Reports whether memory for the container is allocated.
  196. /// </summary>
  197. /// <value>True if this container object's internal storage has been allocated.</value>
  198. /// <remarks>
  199. /// Note that the container storage is not created if you use the default constructor. You must specify
  200. /// at least an allocation type to construct a usable container.
  201. ///
  202. /// *Warning:* the `IsCreated` property can't be used to determine whether a copy of a container is still valid.
  203. /// If you dispose any copy of the container, the container storage is deallocated. However, the properties of
  204. /// the other copies of the container (including the original) are not updated. As a result the `IsCreated` property
  205. /// of the copies still return `true` even though the container storage has been deallocated.
  206. /// </remarks>
  207. public bool IsCreated => Ptr != null;
  208. /// <summary>
  209. /// Disposes of this container and deallocates its memory immediately.
  210. /// </summary>
  211. public void Dispose()
  212. {
  213. if (CollectionHelper.ShouldDeallocate(Allocator))
  214. {
  215. AllocatorManager.Free(Allocator, Ptr);
  216. Allocator = AllocatorManager.Invalid;
  217. }
  218. Ptr = null;
  219. Length = 0;
  220. Capacity = 0;
  221. }
  222. internal void Dispose<U>(ref U allocator, int sizeOf, int alignOf) where U : unmanaged, AllocatorManager.IAllocator
  223. {
  224. allocator.Free(Ptr, sizeOf, alignOf, Length);
  225. Ptr = null;
  226. Length = 0;
  227. Capacity = 0;
  228. }
  229. /// <summary>
  230. /// Safely disposes of this container and deallocates its memory when the jobs that use it have completed.
  231. /// </summary>
  232. /// <remarks>You can call this function dispose of the container immediately after scheduling the job. Pass
  233. /// the [JobHandle](https://docs.unity3d.com/ScriptReference/Unity.Jobs.JobHandle.html) returned by
  234. /// the [Job.Schedule](https://docs.unity3d.com/ScriptReference/Unity.Jobs.IJobExtensions.Schedule.html)
  235. /// method using the `jobHandle` parameter so the job scheduler can dispose the container after all jobs
  236. /// using it have run.</remarks>
  237. /// <param name="inputDeps">The job handle or handles for any scheduled jobs that use this container.</param>
  238. /// <returns>A new job handle containing the prior handles as well as the handle for the job that deletes
  239. /// the container.</returns>
  240. [NotBurstCompatible /* This is not burst compatible because of IJob's use of a static IntPtr. Should switch to IJobBurstSchedulable in the future */]
  241. public JobHandle Dispose(JobHandle inputDeps)
  242. {
  243. if (CollectionHelper.ShouldDeallocate(Allocator))
  244. {
  245. var jobHandle = new UnsafeDisposeJob { Ptr = Ptr, Allocator = (Allocator)Allocator.Value }.Schedule(inputDeps);
  246. Ptr = null;
  247. Allocator = AllocatorManager.Invalid;
  248. return jobHandle;
  249. }
  250. Ptr = null;
  251. return inputDeps;
  252. }
  253. /// <summary>
  254. /// Clears the container.
  255. /// </summary>
  256. /// <remarks>The container capacity remains unchanged.</remarks>
  257. public void Clear()
  258. {
  259. Length = 0;
  260. }
  261. /// <summary>
  262. /// Changes the list length, resizing if necessary.
  263. /// </summary>
  264. /// <param name="sizeOf">Size of element.</param>
  265. /// <param name="alignOf">Alignment of element.</param>
  266. /// <param name="length">The new length of the list.</param>
  267. /// <param name="options">Memory should be cleared on allocation or left uninitialized.</param>
  268. public void Resize(int sizeOf, int alignOf, int length, NativeArrayOptions options = NativeArrayOptions.UninitializedMemory)
  269. {
  270. var oldLength = Length;
  271. if (length > Capacity)
  272. {
  273. SetCapacity(sizeOf, alignOf, length);
  274. }
  275. Length = length;
  276. if (options == NativeArrayOptions.ClearMemory
  277. && oldLength < length)
  278. {
  279. var num = length - oldLength;
  280. byte* ptr = (byte*)Ptr;
  281. UnsafeUtility.MemClear(ptr + oldLength * sizeOf, num * sizeOf);
  282. }
  283. }
  284. /// <summary>
  285. /// Changes the list length, resizing if necessary.
  286. /// </summary>
  287. /// <typeparam name="T">Source type of elements</typeparam>
  288. /// <param name="length">The new length of the list.</param>
  289. /// <param name="options">Memory should be cleared on allocation or left uninitialized.</param>
  290. public void Resize<T>(int length, NativeArrayOptions options = NativeArrayOptions.UninitializedMemory) where T : struct
  291. {
  292. Resize(UnsafeUtility.SizeOf<T>(), UnsafeUtility.AlignOf<T>(), length, options);
  293. }
  294. void Realloc<U>(ref U allocator, int sizeOf, int alignOf, int capacity) where U : unmanaged, AllocatorManager.IAllocator
  295. {
  296. void* newPointer = null;
  297. if (capacity > 0)
  298. {
  299. newPointer = allocator.Allocate(sizeOf, alignOf, capacity);
  300. if (Capacity > 0)
  301. {
  302. var itemsToCopy = math.min(capacity, Capacity);
  303. var bytesToCopy = itemsToCopy * sizeOf;
  304. UnsafeUtility.MemCpy(newPointer, Ptr, bytesToCopy);
  305. }
  306. }
  307. allocator.Free(Ptr, sizeOf, alignOf, Capacity);
  308. Ptr = newPointer;
  309. Capacity = capacity;
  310. Length = math.min(Length, capacity);
  311. }
  312. void Realloc(int sizeOf, int alignOf, int capacity)
  313. {
  314. Realloc(ref Allocator, sizeOf, alignOf, capacity);
  315. }
  316. void SetCapacity<U>(ref U allocator, int sizeOf, int alignOf, int capacity) where U : unmanaged, AllocatorManager.IAllocator
  317. {
  318. var newCapacity = math.max(capacity, 64 / sizeOf);
  319. newCapacity = math.ceilpow2(newCapacity);
  320. if (newCapacity == Capacity)
  321. {
  322. return;
  323. }
  324. Realloc(ref allocator, sizeOf, alignOf, newCapacity);
  325. }
  326. void SetCapacity(int sizeOf, int alignOf, int capacity)
  327. {
  328. SetCapacity(ref Allocator, sizeOf, alignOf, capacity);
  329. }
  330. /// <summary>
  331. /// Set the number of items that can fit in the container.
  332. /// </summary>
  333. /// <typeparam name="T">Source type of elements</typeparam>
  334. /// <param name="capacity">The number of items that the container can hold before it resizes its internal storage.</param>
  335. public void SetCapacity<T>(int capacity) where T : struct
  336. {
  337. SetCapacity(UnsafeUtility.SizeOf<T>(), UnsafeUtility.AlignOf<T>(), capacity);
  338. }
  339. /// <summary>
  340. /// Sets the capacity to the actual number of elements in the container.
  341. /// </summary>
  342. /// <typeparam name="T">Source type of elements</typeparam>
  343. public void TrimExcess<T>() where T : struct
  344. {
  345. if (Capacity != Length)
  346. {
  347. Realloc(UnsafeUtility.SizeOf<T>(), UnsafeUtility.AlignOf<T>(), Length);
  348. }
  349. }
  350. /// <summary>
  351. /// Searches for the specified element in list.
  352. /// </summary>
  353. /// <typeparam name="T">Source type of elements</typeparam>
  354. /// <param name="value"></param>
  355. /// <returns>The zero-based index of the first occurrence element if found, otherwise returns -1.</returns>
  356. public int IndexOf<T>(T value) where T : struct, IEquatable<T>
  357. {
  358. return NativeArrayExtensions.IndexOf<T, T>(Ptr, Length, value);
  359. }
  360. /// <summary>
  361. /// Determines whether an element is in the list.
  362. /// </summary>
  363. /// <typeparam name="T">Source type of elements</typeparam>
  364. /// <param name="value"></param>
  365. /// <returns>True, if element is found.</returns>
  366. public bool Contains<T>(T value) where T : struct, IEquatable<T>
  367. {
  368. return IndexOf(value) != -1;
  369. }
  370. /// <summary>
  371. /// Adds an element to the list.
  372. /// </summary>
  373. /// <typeparam name="T">Source type of elements</typeparam>
  374. /// <param name="value">The value to be added at the end of the list.</param>
  375. /// <remarks>
  376. /// If the list has reached its current capacity, internal array won't be resized, and exception will be thrown.
  377. /// </remarks>
  378. public void AddNoResize<T>(T value) where T : struct
  379. {
  380. CheckNoResizeHasEnoughCapacity(1);
  381. UnsafeUtility.WriteArrayElement(Ptr, Length, value);
  382. Length += 1;
  383. }
  384. void AddRangeNoResize(int sizeOf, void* ptr, int length)
  385. {
  386. CheckNoResizeHasEnoughCapacity(length);
  387. void* dst = (byte*)Ptr + Length * sizeOf;
  388. UnsafeUtility.MemCpy(dst, ptr, length * sizeOf);
  389. Length += length;
  390. }
  391. /// <summary>
  392. /// Adds elements from a buffer to this list.
  393. /// </summary>
  394. /// <typeparam name="T">Source type of elements</typeparam>
  395. /// <param name="ptr">A pointer to the buffer.</param>
  396. /// <param name="length">The number of elements to add to the list.</param>
  397. /// <remarks>
  398. /// If the list has reached its current capacity, internal array won't be resized, and exception will be thrown.
  399. /// </remarks>
  400. public void AddRangeNoResize<T>(void* ptr, int length) where T : struct
  401. {
  402. AddRangeNoResize(UnsafeUtility.SizeOf<T>(), ptr, length);
  403. }
  404. /// <summary>
  405. /// Adds elements from a list to this list.
  406. /// </summary>
  407. /// <typeparam name="T">Source type of elements</typeparam>
  408. /// <param name="list">Other container to copy elements from.</param>
  409. /// <remarks>
  410. /// If the list has reached its current capacity, internal array won't be resized, and exception will be thrown.
  411. /// </remarks>
  412. public void AddRangeNoResize<T>(UnsafeList list) where T : struct
  413. {
  414. AddRangeNoResize(UnsafeUtility.SizeOf<T>(), list.Ptr, CollectionHelper.AssumePositive(list.Length));
  415. }
  416. /// <summary>
  417. /// Adds an element to the list.
  418. /// </summary>
  419. /// <typeparam name="T">Source type of elements</typeparam>
  420. /// <param name="value">The value to be added at the end of the list.</param>
  421. /// <remarks>
  422. /// If the list has reached its current capacity, it copies the original, internal array to
  423. /// a new, larger array, and then deallocates the original.
  424. /// </remarks>
  425. public void Add<T>(T value) where T : struct
  426. {
  427. var idx = Length;
  428. if (Length + 1 > Capacity)
  429. {
  430. Resize<T>(idx + 1);
  431. }
  432. else
  433. {
  434. Length += 1;
  435. }
  436. UnsafeUtility.WriteArrayElement(Ptr, idx, value);
  437. }
  438. void AddRange(int sizeOf, int alignOf, void* ptr, int length)
  439. {
  440. var idx = Length;
  441. if (Length + length > Capacity)
  442. {
  443. Resize(sizeOf, alignOf, Length + length);
  444. }
  445. else
  446. {
  447. Length += length;
  448. }
  449. void* dst = (byte*)Ptr + idx * sizeOf;
  450. UnsafeUtility.MemCpy(dst, ptr, length * sizeOf);
  451. }
  452. /// <summary>
  453. /// Adds elements from a buffer to this list.
  454. /// </summary>
  455. /// <typeparam name="T">Source type of elements</typeparam>
  456. /// <param name="ptr">A pointer to the buffer.</param>
  457. /// <param name="length">The number of elements to add to the list.</param>
  458. public void AddRange<T>(void* ptr, int length) where T : struct
  459. {
  460. AddRange(UnsafeUtility.SizeOf<T>(), UnsafeUtility.AlignOf<T>(), ptr, length);
  461. }
  462. /// <summary>
  463. /// Adds elements from a list to this list.
  464. /// </summary>
  465. /// <remarks>
  466. /// If the list has reached its current capacity, it copies the original, internal array to
  467. /// a new, larger array, and then deallocates the original.
  468. /// </remarks>
  469. /// <typeparam name="T">Source type of elements</typeparam>
  470. /// <param name="list">Other container to copy elements from.</param>
  471. public void AddRange<T>(UnsafeList list) where T : struct
  472. {
  473. AddRange(UnsafeUtility.SizeOf<T>(), UnsafeUtility.AlignOf<T>(), list.Ptr, list.Length);
  474. }
  475. void InsertRangeWithBeginEnd(int sizeOf, int alignOf, int begin, int end)
  476. {
  477. CheckBeginEnd(begin, end);
  478. int items = end - begin;
  479. if (items < 1)
  480. {
  481. return;
  482. }
  483. var oldLength = Length;
  484. if (Length + items > Capacity)
  485. {
  486. Resize(sizeOf, alignOf, Length + items);
  487. }
  488. else
  489. {
  490. Length += items;
  491. }
  492. var itemsToCopy = oldLength - begin;
  493. if (itemsToCopy < 1)
  494. {
  495. return;
  496. }
  497. var bytesToCopy = itemsToCopy * sizeOf;
  498. unsafe
  499. {
  500. byte* ptr = (byte*)Ptr;
  501. byte* dest = ptr + end * sizeOf;
  502. byte* src = ptr + begin * sizeOf;
  503. UnsafeUtility.MemMove(dest, src, bytesToCopy);
  504. }
  505. }
  506. /// <summary>
  507. /// Inserts a number of items into a container at a specified zero-based index.
  508. /// </summary>
  509. /// <typeparam name="T">Source type of elements</typeparam>
  510. /// <param name="begin">The zero-based index at which the new elements should be inserted.</param>
  511. /// <param name="end">The zero-based index just after where the elements should be removed.</param>
  512. /// <exception cref="ArgumentException">Thrown if end argument is less than begin argument.</exception>
  513. /// <exception cref="ArgumentOutOfRangeException">Thrown if begin or end arguments are not positive or out of bounds.</exception>
  514. public void InsertRangeWithBeginEnd<T>(int begin, int end) where T : struct
  515. {
  516. InsertRangeWithBeginEnd(UnsafeUtility.SizeOf<T>(), UnsafeUtility.AlignOf<T>(), begin, end);
  517. }
  518. void RemoveRangeSwapBackWithBeginEnd(int sizeOf, int begin, int end)
  519. {
  520. CheckBeginEnd(begin, end);
  521. int itemsToRemove = end - begin;
  522. if (itemsToRemove > 0)
  523. {
  524. int copyFrom = math.max(Length - itemsToRemove, end);
  525. void* dst = (byte*)Ptr + begin * sizeOf;
  526. void* src = (byte*)Ptr + copyFrom * sizeOf;
  527. UnsafeUtility.MemCpy(dst, src, (Length - copyFrom) * sizeOf);
  528. Length -= itemsToRemove;
  529. }
  530. }
  531. /// <summary>
  532. /// Truncates the list by replacing the item at the specified index with the last item in the list. The list
  533. /// is shortened by one.
  534. /// </summary>
  535. /// <typeparam name="T">Source type of elements</typeparam>
  536. /// <param name="index">The index of the item to delete.</param>
  537. /// <exception cref="ArgumentException">Thrown if end argument is less than begin argument.</exception>
  538. /// <exception cref="ArgumentOutOfRangeException">Thrown if begin or end arguments are not positive or out of bounds.</exception>
  539. public void RemoveAtSwapBack<T>(int index) where T : struct
  540. {
  541. RemoveRangeSwapBackWithBeginEnd<T>(index, index + 1);
  542. }
  543. /// <summary>
  544. /// Truncates the list by replacing the item at the specified index range with the items from the end the list. The list
  545. /// is shortened by number of elements in range.
  546. /// </summary>
  547. /// <typeparam name="T">Source type of elements</typeparam>
  548. /// <param name="begin">The first index of the item to remove.</param>
  549. /// <param name="end">The index past-the-last item to remove.</param>
  550. /// <exception cref="ArgumentException">Thrown if end argument is less than begin argument.</exception>
  551. /// <exception cref="ArgumentOutOfRangeException">Thrown if begin or end arguments are not positive or out of bounds.</exception>
  552. public void RemoveRangeSwapBackWithBeginEnd<T>(int begin, int end) where T : struct
  553. {
  554. RemoveRangeSwapBackWithBeginEnd(UnsafeUtility.SizeOf<T>(), begin, end);
  555. }
  556. void RemoveRangeWithBeginEnd(int sizeOf, int begin, int end)
  557. {
  558. CheckBeginEnd(begin, end);
  559. int itemsToRemove = end - begin;
  560. if (itemsToRemove > 0)
  561. {
  562. int copyFrom = math.min(begin + itemsToRemove, Length);
  563. void* dst = (byte*)Ptr + begin * sizeOf;
  564. void* src = (byte*)Ptr + copyFrom * sizeOf;
  565. UnsafeUtility.MemCpy(dst, src, (Length - copyFrom) * sizeOf);
  566. Length -= itemsToRemove;
  567. }
  568. }
  569. /// <summary>
  570. /// Truncates the list by removing the item at the specified index, and shifting all remaining items to replace removed item. The list
  571. /// is shortened by one.
  572. /// </summary>
  573. /// <typeparam name="T">Source type of elements</typeparam>
  574. /// <param name="index">The index of the item to delete.</param>
  575. /// <remarks>
  576. /// This method of removing item is useful only in case when list is ordered and user wants to preserve order
  577. /// in list after removal In majority of cases is not important and user should use more performant `RemoveAtSwapBack`.
  578. /// </remarks>
  579. public void RemoveAt<T>(int index) where T : struct
  580. {
  581. RemoveRangeWithBeginEnd<T>(index, index + 1);
  582. }
  583. /// <summary>
  584. /// Truncates the list by removing the items at the specified index range, and shifting all remaining items to replace removed items. The list
  585. /// is shortened by number of elements in range.
  586. /// </summary>
  587. /// <typeparam name="T">Source type of elements</typeparam>
  588. /// <param name="begin">The first index of the item to remove.</param>
  589. /// <param name="end">The index past-the-last item to remove.</param>
  590. /// <remarks>
  591. /// This method of removing item(s) is useful only in case when list is ordered and user wants to preserve order
  592. /// in list after removal In majority of cases is not important and user should use more performant `RemoveRangeSwapBackWithBeginEnd`.
  593. /// </remarks>
  594. /// <exception cref="ArgumentException">Thrown if end argument is less than begin argument.</exception>
  595. /// <exception cref="ArgumentOutOfRangeException">Thrown if begin or end arguments are not positive or out of bounds.</exception>
  596. public void RemoveRangeWithBeginEnd<T>(int begin, int end) where T : struct
  597. {
  598. RemoveRangeWithBeginEnd(UnsafeUtility.SizeOf<T>(), begin, end);
  599. }
  600. /// <summary>
  601. /// Returns parallel reader instance.
  602. /// </summary>
  603. /// <returns>Parallel reader instance.</returns>
  604. public ParallelReader AsParallelReader()
  605. {
  606. return new ParallelReader(Ptr, Length);
  607. }
  608. /// <summary>
  609. /// Implements parallel reader. Use AsParallelReader to obtain it from container.
  610. /// </summary>
  611. public unsafe struct ParallelReader
  612. {
  613. /// <summary>
  614. ///
  615. /// </summary>
  616. [NativeDisableUnsafePtrRestriction]
  617. public readonly void* Ptr;
  618. /// <summary>
  619. ///
  620. /// </summary>
  621. public readonly int Length;
  622. internal ParallelReader(void* ptr, int length)
  623. {
  624. Ptr = ptr;
  625. Length = length;
  626. }
  627. /// <summary>
  628. ///
  629. /// </summary>
  630. /// <typeparam name="T"></typeparam>
  631. /// <param name="value"></param>
  632. /// <returns></returns>
  633. public int IndexOf<T>(T value) where T : struct, IEquatable<T>
  634. {
  635. return NativeArrayExtensions.IndexOf<T, T>(Ptr, Length, value);
  636. }
  637. /// <summary>
  638. ///
  639. /// </summary>
  640. /// <typeparam name="T"></typeparam>
  641. /// <param name="value"></param>
  642. /// <returns></returns>
  643. public bool Contains<T>(T value) where T : struct, IEquatable<T>
  644. {
  645. return IndexOf(value) != -1;
  646. }
  647. }
  648. /// <summary>
  649. /// Returns parallel writer instance.
  650. /// </summary>
  651. /// <returns>Parallel writer instance.</returns>
  652. public ParallelWriter AsParallelWriter()
  653. {
  654. return new ParallelWriter(Ptr, (UnsafeList*)UnsafeUtility.AddressOf(ref this));
  655. }
  656. /// <summary>
  657. ///
  658. /// </summary>
  659. public unsafe struct ParallelWriter
  660. {
  661. /// <summary>
  662. ///
  663. /// </summary>
  664. [NativeDisableUnsafePtrRestriction]
  665. public readonly void* Ptr;
  666. /// <summary>
  667. ///
  668. /// </summary>
  669. [NativeDisableUnsafePtrRestriction]
  670. public UnsafeList* ListData;
  671. internal unsafe ParallelWriter(void* ptr, UnsafeList* listData)
  672. {
  673. Ptr = ptr;
  674. ListData = listData;
  675. }
  676. /// <summary>
  677. /// Adds an element to the list.
  678. /// </summary>
  679. /// <typeparam name="T">Source type of elements</typeparam>
  680. /// <param name="value">The value to be added at the end of the list.</param>
  681. /// <remarks>
  682. /// If the list has reached its current capacity, internal array won't be resized, and exception will be thrown.
  683. /// </remarks>
  684. public void AddNoResize<T>(T value) where T : struct
  685. {
  686. var idx = Interlocked.Increment(ref ListData->Length) - 1;
  687. ListData->CheckNoResizeHasEnoughCapacity(idx, 1);
  688. UnsafeUtility.WriteArrayElement(Ptr, idx, value);
  689. }
  690. void AddRangeNoResize(int sizeOf, int alignOf, void* ptr, int length)
  691. {
  692. var idx = Interlocked.Add(ref ListData->Length, length) - length;
  693. ListData->CheckNoResizeHasEnoughCapacity(idx, length);
  694. void* dst = (byte*)Ptr + idx * sizeOf;
  695. UnsafeUtility.MemCpy(dst, ptr, length * sizeOf);
  696. }
  697. /// <summary>
  698. /// Adds elements from a buffer to this list.
  699. /// </summary>
  700. /// <typeparam name="T">Source type of elements</typeparam>
  701. /// <param name="ptr">A pointer to the buffer.</param>
  702. /// <param name="length">The number of elements to add to the list.</param>
  703. /// <remarks>
  704. /// If the list has reached its current capacity, internal array won't be resized, and exception will be thrown.
  705. /// </remarks>
  706. public void AddRangeNoResize<T>(void* ptr, int length) where T : struct
  707. {
  708. AddRangeNoResize(UnsafeUtility.SizeOf<T>(), UnsafeUtility.AlignOf<T>(), ptr, length);
  709. }
  710. /// <summary>
  711. /// Adds elements from a list to this list.
  712. /// </summary>
  713. /// <typeparam name="T">Source type of elements</typeparam>
  714. /// <param name="list">Other container to copy elements from.</param>
  715. /// <remarks>
  716. /// If the list has reached its current capacity, internal array won't be resized, and exception will be thrown.
  717. /// </remarks>
  718. public void AddRangeNoResize<T>(UnsafeList list) where T : struct
  719. {
  720. AddRangeNoResize(UnsafeUtility.SizeOf<T>(), UnsafeUtility.AlignOf<T>(), list.Ptr, list.Length);
  721. }
  722. }
  723. [Conditional("ENABLE_UNITY_COLLECTIONS_CHECKS")]
  724. internal static void CheckNull(void* listData)
  725. {
  726. if (listData == null)
  727. {
  728. throw new Exception("UnsafeList has yet to be created or has been destroyed!");
  729. }
  730. }
  731. [Conditional("ENABLE_UNITY_COLLECTIONS_CHECKS")]
  732. static void CheckAllocator(Allocator a)
  733. {
  734. if (!CollectionHelper.ShouldDeallocate(a))
  735. {
  736. throw new Exception("UnsafeList is not initialized, it must be initialized with allocator before use.");
  737. }
  738. }
  739. [Conditional("ENABLE_UNITY_COLLECTIONS_CHECKS")]
  740. static void CheckAllocator(AllocatorManager.AllocatorHandle a)
  741. {
  742. if (!CollectionHelper.ShouldDeallocate(a))
  743. {
  744. throw new Exception("UnsafeList is not initialized, it must be initialized with allocator before use.");
  745. }
  746. }
  747. [Conditional("ENABLE_UNITY_COLLECTIONS_CHECKS")]
  748. void CheckBeginEnd(int begin, int end)
  749. {
  750. if (begin > end)
  751. {
  752. throw new ArgumentException($"Value for begin {begin} index must less or equal to end {end}.");
  753. }
  754. if (begin < 0)
  755. {
  756. throw new ArgumentOutOfRangeException($"Value for begin {begin} must be positive.");
  757. }
  758. if (begin > Length)
  759. {
  760. throw new ArgumentOutOfRangeException($"Value for begin {begin} is out of bounds.");
  761. }
  762. if (end > Length)
  763. {
  764. throw new ArgumentOutOfRangeException($"Value for end {end} is out of bounds.");
  765. }
  766. }
  767. [Conditional("ENABLE_UNITY_COLLECTIONS_CHECKS")]
  768. void CheckNoResizeHasEnoughCapacity(int length)
  769. {
  770. CheckNoResizeHasEnoughCapacity(length, Length);
  771. }
  772. [Conditional("ENABLE_UNITY_COLLECTIONS_CHECKS")]
  773. void CheckNoResizeHasEnoughCapacity(int length, int index)
  774. {
  775. if (Capacity < index + length)
  776. {
  777. throw new Exception($"AddNoResize assumes that list capacity is sufficient (Capacity {Capacity}, Length {Length}), requested length {length}!");
  778. }
  779. }
  780. }
  781. /// <summary>
  782. /// Provides extension methods for UnsafeList.
  783. /// </summary>
  784. public static class UnsafeListExtension
  785. {
  786. [BurstCompatible(GenericTypeArguments = new[] { typeof(int) })]
  787. internal static ref UnsafeList ListData<T>(ref this UnsafeList<T> from) where T : unmanaged => ref UnsafeUtility.As<UnsafeList<T>, UnsafeList>(ref from);
  788. /// <summary>
  789. /// Sorts a list in ascending order.
  790. /// </summary>
  791. /// <typeparam name="T">Source type of elements</typeparam>
  792. /// <param name="list">List to perform sort.</param>
  793. public unsafe static void Sort<T>(this UnsafeList list) where T : unmanaged, IComparable<T>
  794. {
  795. list.Sort<T, NativeSortExtension.DefaultComparer<T>>(new NativeSortExtension.DefaultComparer<T>());
  796. }
  797. /// <summary>
  798. /// Sorts a list using a custom comparison function.
  799. /// </summary>
  800. /// <typeparam name="T">Source type of elements</typeparam>
  801. /// <typeparam name="U">The comparer type.</typeparam>
  802. /// <param name="list">List to perform sort.</param>
  803. /// <param name="comp">A comparison function that indicates whether one element in the array is less than, equal to, or greater than another element.</param>
  804. public unsafe static void Sort<T, U>(this UnsafeList list, U comp) where T : unmanaged where U : IComparer<T>
  805. {
  806. NativeSortExtension.IntroSort<T, U>(list.Ptr, list.Length, comp);
  807. }
  808. /// <summary>
  809. /// Sorts the container in ascending order.
  810. /// </summary>
  811. /// <typeparam name="T">Source type of elements</typeparam>
  812. /// <param name="container">The container to perform sort.</param>
  813. /// <param name="inputDeps">The job handle or handles for any scheduled jobs that use this container.</param>
  814. /// <returns>A new job handle containing the prior handles as well as the handle for the job that sorts
  815. /// the container.</returns>
  816. [NotBurstCompatible /* This is not burst compatible because of IJob's use of a static IntPtr. Should switch to IJobBurstSchedulable in the future */]
  817. [Obsolete("Instead call SortJob(this UnsafeList).Schedule(JobHandle). (RemovedAfter 2021-06-20)", false)]
  818. public unsafe static JobHandle Sort<T>(this UnsafeList container, JobHandle inputDeps)
  819. where T : unmanaged, IComparable<T>
  820. {
  821. return container.Sort<T, NativeSortExtension.DefaultComparer<T>>(new NativeSortExtension.DefaultComparer<T>(), inputDeps);
  822. }
  823. /// <summary>
  824. /// Creates a job that will sort a list in ascending order.
  825. /// </summary>
  826. /// <typeparam name="T">Source type of elements</typeparam>
  827. /// <param name="list">List to sort.</param>
  828. /// <returns>The job that will sort the list. Scheduling the job is left to the user.</returns>
  829. public unsafe static SortJob<T, NativeSortExtension.DefaultComparer<T>> SortJob<T>(this UnsafeList list)
  830. where T : unmanaged, IComparable<T>
  831. {
  832. return NativeSortExtension.SortJob((T*)list.Ptr, list.Length, new NativeSortExtension.DefaultComparer<T>());
  833. }
  834. /// <summary>
  835. /// Sorts the container using a custom comparison function.
  836. /// </summary>
  837. /// <typeparam name="T">Source type of elements</typeparam>
  838. /// <typeparam name="U">The comparer type.</typeparam>
  839. /// <param name="container">The container to perform sort.</param>
  840. /// <param name="comp">A comparison function that indicates whether one element in the array is less than, equal to, or greater than another element.</param>
  841. /// <param name="inputDeps">The job handle or handles for any scheduled jobs that use this container.</param>
  842. /// <returns>A new job handle containing the prior handles as well as the handle for the job that sorts
  843. /// the container.</returns>
  844. [NotBurstCompatible /* This is not burst compatible because of IJob's use of a static IntPtr. Should switch to IJobBurstSchedulable in the future */]
  845. [Obsolete("Instead call SortJob(this UnsafeList, U).Schedule(JobHandle). (RemovedAfter 2021-06-20)", false)]
  846. public unsafe static JobHandle Sort<T, U>(this UnsafeList container, U comp, JobHandle inputDeps)
  847. where T : unmanaged
  848. where U : IComparer<T>
  849. {
  850. return NativeSortExtension.Sort((T*)container.Ptr, container.Length, comp, inputDeps);
  851. }
  852. /// <summary>
  853. /// Creates a job that will sort a list using a comparison function.
  854. /// </summary>
  855. /// <typeparam name="T">Source type of elements</typeparam>
  856. /// <typeparam name="U">The comparer type.</typeparam>
  857. /// <param name="list">List to sort.</param>
  858. /// <param name="comp">A comparison function that indicates whether one element in the array is less than, equal to, or greater than another element.</param>
  859. /// <returns>The job that will sort the list. Scheduling the job is left to the user.</returns>
  860. public unsafe static SortJob<T, U> SortJob<T, U>(this UnsafeList list, U comp)
  861. where T : unmanaged
  862. where U : IComparer<T>
  863. {
  864. return NativeSortExtension.SortJob((T*)list.Ptr, list.Length, comp);
  865. }
  866. /// <summary>
  867. /// Binary search for the value in the sorted container.
  868. /// </summary>
  869. /// <typeparam name="T">Source type of elements</typeparam>
  870. /// <param name="container">The container to perform search.</param>
  871. /// <param name="value">The value to search for.</param>
  872. /// <returns>Positive index of the specified value if value is found. Otherwise bitwise complement of index of first greater value.</returns>
  873. /// <remarks>Array must be sorted, otherwise value searched might not be found even when it is in array. IComparer corresponds to IComparer used by sort.</remarks>
  874. public static int BinarySearch<T>(this UnsafeList container, T value)
  875. where T : unmanaged, IComparable<T>
  876. {
  877. return container.BinarySearch(value, new NativeSortExtension.DefaultComparer<T>());
  878. }
  879. /// <summary>
  880. /// Binary search for the value in the sorted container.
  881. /// </summary>
  882. /// <typeparam name="T">Source type of elements</typeparam>
  883. /// <typeparam name="U">The comparer type.</typeparam>
  884. /// <param name="container">The container to perform search.</param>
  885. /// <param name="value">The value to search for.</param>
  886. /// <param name="comp">A comparison function that indicates whether one element in the array is less than, equal to, or greater than another element.</param>
  887. /// <returns>Positive index of the specified value if value is found. Otherwise bitwise complement of index of first greater value.</returns>
  888. /// <remarks>Array must be sorted, otherwise value searched might not be found even when it is in array. IComparer corresponds to IComparer used by sort.</remarks>
  889. public unsafe static int BinarySearch<T, U>(this UnsafeList container, T value, U comp)
  890. where T : unmanaged
  891. where U : IComparer<T>
  892. {
  893. return NativeSortExtension.BinarySearch((T*)container.Ptr, container.Length, value, comp);
  894. }
  895. }
  896. /// <summary>
  897. /// An unmanaged, resizable list, without any thread safety check features.
  898. /// </summary>
  899. [DebuggerDisplay("Length = {Length}, Capacity = {Capacity}, IsCreated = {IsCreated}, IsEmpty = {IsEmpty}")]
  900. [DebuggerTypeProxy(typeof(UnsafePtrListDebugView))]
  901. [Obsolete("Untyped UnsafePtrList is deprecated, please use UnsafePtrList<T> instead. (RemovedAfter 2021-05-18)", false)]
  902. public unsafe struct UnsafePtrList
  903. : INativeDisposable
  904. , INativeList<IntPtr>
  905. , IEnumerable<IntPtr> // Used by collection initializers.
  906. {
  907. /// <summary>
  908. ///
  909. /// </summary>
  910. [NativeDisableUnsafePtrRestriction]
  911. public readonly void** Ptr;
  912. /// <summary>
  913. ///
  914. /// </summary>
  915. public readonly int length;
  916. public readonly int unused;
  917. /// <summary>
  918. ///
  919. /// </summary>
  920. public readonly int capacity;
  921. /// <summary>
  922. ///
  923. /// </summary>
  924. public readonly AllocatorManager.AllocatorHandle Allocator;
  925. /// <summary>
  926. ///
  927. /// </summary>
  928. public int Length { get { return length; } set { } }
  929. /// <summary>
  930. ///
  931. /// </summary>
  932. public int Capacity { get { return capacity; } set { } }
  933. /// <summary>
  934. ///
  935. /// </summary>
  936. /// <param name="index"></param>
  937. /// <returns></returns>
  938. public IntPtr this[int index]
  939. {
  940. get { return new IntPtr(Ptr[index]); }
  941. set { Ptr[index] = (void*)value; }
  942. }
  943. /// <summary>
  944. ///
  945. /// </summary>
  946. /// <param name="index"></param>
  947. /// <returns></returns>
  948. public ref IntPtr ElementAt(int index)
  949. {
  950. return ref ((IntPtr*)Ptr)[index];
  951. }
  952. /// <summary>
  953. /// Constructs list as view into memory.
  954. /// </summary>
  955. /// <param name="ptr"></param>
  956. /// <param name="length"></param>
  957. public unsafe UnsafePtrList(void** ptr, int length) : this()
  958. {
  959. Ptr = ptr;
  960. this.length = length;
  961. this.capacity = length;
  962. Allocator = AllocatorManager.None;
  963. }
  964. /// <summary>
  965. /// Constructs a new list using the specified type of memory allocation.
  966. /// </summary>
  967. /// <param name="initialCapacity">The initial capacity of the list. If the list grows larger than its capacity,
  968. /// the internal array is copied to a new, larger array.</param>
  969. /// <param name="allocator">A member of the
  970. /// [Unity.Collections.Allocator](https://docs.unity3d.com/ScriptReference/Unity.Collections.Allocator.html) enumeration.</param>
  971. /// <param name="options">Memory should be cleared on allocation or left uninitialized.</param>
  972. /// <remarks>The list initially has a capacity of one. To avoid reallocating memory for the list, specify
  973. /// sufficient capacity up front.</remarks>
  974. public unsafe UnsafePtrList(int initialCapacity, AllocatorManager.AllocatorHandle allocator, NativeArrayOptions options = NativeArrayOptions.UninitializedMemory) : this()
  975. {
  976. Ptr = null;
  977. length = 0;
  978. capacity = 0;
  979. Allocator = AllocatorManager.None;
  980. var sizeOf = IntPtr.Size;
  981. this.ListData() = new UnsafeList(sizeOf, sizeOf, initialCapacity, allocator, options);
  982. }
  983. /// <summary>
  984. /// Constructs a new list using the specified type of memory allocation.
  985. /// </summary>
  986. /// <param name="initialCapacity">The initial capacity of the list. If the list grows larger than its capacity,
  987. /// the internal array is copied to a new, larger array.</param>
  988. /// <param name="allocator">A member of the
  989. /// [Unity.Collections.Allocator](https://docs.unity3d.com/ScriptReference/Unity.Collections.Allocator.html) enumeration.</param>
  990. /// <param name="options">Memory should be cleared on allocation or left uninitialized.</param>
  991. /// <remarks>The list initially has a capacity of one. To avoid reallocating memory for the list, specify
  992. /// sufficient capacity up front.</remarks>
  993. public unsafe UnsafePtrList(int initialCapacity, Allocator allocator, NativeArrayOptions options = NativeArrayOptions.UninitializedMemory) : this()
  994. {
  995. Ptr = null;
  996. length = 0;
  997. capacity = 0;
  998. Allocator = AllocatorManager.None;
  999. var sizeOf = IntPtr.Size;
  1000. this.ListData() = new UnsafeList(sizeOf, sizeOf, initialCapacity, allocator, options);
  1001. }
  1002. /// <summary>
  1003. ///
  1004. /// </summary>
  1005. /// <param name="ptr"></param>
  1006. /// <param name="length"></param>
  1007. /// <returns>New initialized container.</returns>
  1008. public static UnsafePtrList* Create(void** ptr, int length)
  1009. {
  1010. UnsafePtrList* listData = AllocatorManager.Allocate<UnsafePtrList>(AllocatorManager.Persistent);
  1011. *listData = new UnsafePtrList(ptr, length);
  1012. return listData;
  1013. }
  1014. /// <summary>
  1015. /// Creates a new list with the specified initial capacity and type of memory allocation.
  1016. /// </summary>
  1017. /// <param name="initialCapacity">The initial capacity of the list. If the list grows larger than its capacity,
  1018. /// the internal array is copied to a new, larger array.</param>
  1019. /// <param name="allocator">A member of the
  1020. /// [Unity.Collections.Allocator](https://docs.unity3d.com/ScriptReference/Unity.Collections.Allocator.html) enumeration.</param>
  1021. /// <param name="options">Memory should be cleared on allocation or left uninitialized.</param>
  1022. /// <returns>New initialized container.</returns>
  1023. public static UnsafePtrList* Create(int initialCapacity, Allocator allocator, NativeArrayOptions options = NativeArrayOptions.UninitializedMemory)
  1024. {
  1025. UnsafePtrList* listData = AllocatorManager.Allocate<UnsafePtrList>(allocator);
  1026. *listData = new UnsafePtrList(initialCapacity, allocator, options);
  1027. return listData;
  1028. }
  1029. /// <summary>
  1030. /// Destroys list.
  1031. /// </summary>
  1032. /// <param name="listData">Container to destroy.</param>
  1033. public static void Destroy(UnsafePtrList* listData)
  1034. {
  1035. UnsafeList.CheckNull(listData);
  1036. var allocator = listData->ListData().Allocator.Value == AllocatorManager.Invalid.Value
  1037. ? AllocatorManager.Persistent
  1038. : listData->ListData().Allocator
  1039. ;
  1040. listData->Dispose();
  1041. AllocatorManager.Free(allocator, listData);
  1042. }
  1043. /// <summary>
  1044. /// Reports whether container is empty.
  1045. /// </summary>
  1046. /// <value>True if this string has no characters or if the container has not been constructed.</value>
  1047. public bool IsEmpty => !IsCreated || Length == 0;
  1048. /// <summary>
  1049. /// Reports whether memory for the container is allocated.
  1050. /// </summary>
  1051. /// <value>True if this container object's internal storage has been allocated.</value>
  1052. /// <remarks>
  1053. /// Note that the container storage is not created if you use the default constructor. You must specify
  1054. /// at least an allocation type to construct a usable container.
  1055. ///
  1056. /// *Warning:* the `IsCreated` property can't be used to determine whether a copy of a container is still valid.
  1057. /// If you dispose any copy of the container, the container storage is deallocated. However, the properties of
  1058. /// the other copies of the container (including the original) are not updated. As a result the `IsCreated` property
  1059. /// of the copies still return `true` even though the container storage has been deallocated.
  1060. /// </remarks>
  1061. public bool IsCreated => Ptr != null;
  1062. /// <summary>
  1063. /// Disposes of this container and deallocates its memory immediately.
  1064. /// </summary>
  1065. public void Dispose()
  1066. {
  1067. this.ListData().Dispose();
  1068. }
  1069. /// <summary>
  1070. /// Safely disposes of this container and deallocates its memory when the jobs that use it have completed.
  1071. /// </summary>
  1072. /// <remarks>You can call this function dispose of the container immediately after scheduling the job. Pass
  1073. /// the [JobHandle](https://docs.unity3d.com/ScriptReference/Unity.Jobs.JobHandle.html) returned by
  1074. /// the [Job.Schedule](https://docs.unity3d.com/ScriptReference/Unity.Jobs.IJobExtensions.Schedule.html)
  1075. /// method using the `jobHandle` parameter so the job scheduler can dispose the container after all jobs
  1076. /// using it have run.</remarks>
  1077. /// <param name="inputDeps">The job handle or handles for any scheduled jobs that use this container.</param>
  1078. /// <returns>A new job handle containing the prior handles as well as the handle for the job that deletes
  1079. /// the container.</returns>
  1080. [NotBurstCompatible /* This is not burst compatible because of IJob's use of a static IntPtr. Should switch to IJobBurstSchedulable in the future */]
  1081. public JobHandle Dispose(JobHandle inputDeps)
  1082. {
  1083. return this.ListData().Dispose(inputDeps);
  1084. }
  1085. /// <summary>
  1086. /// Clears the list.
  1087. /// </summary>
  1088. /// <remarks>List Capacity remains unchanged.</remarks>
  1089. public void Clear()
  1090. {
  1091. this.ListData().Clear();
  1092. }
  1093. /// <summary>
  1094. /// Changes the list length, resizing if necessary.
  1095. /// </summary>
  1096. /// <param name="length">The new length of the list.</param>
  1097. /// <param name="options">Memory should be cleared on allocation or left uninitialized.</param>
  1098. public void Resize(int length, NativeArrayOptions options = NativeArrayOptions.UninitializedMemory)
  1099. {
  1100. this.ListData().Resize<IntPtr>(length, options);
  1101. }
  1102. /// <summary>
  1103. /// Set the number of items that can fit in the list.
  1104. /// </summary>
  1105. /// <param name="capacity">The number of items that the list can hold before it resizes its internal storage.</param>
  1106. public void SetCapacity(int capacity)
  1107. {
  1108. this.ListData().SetCapacity<IntPtr>(capacity);
  1109. }
  1110. /// <summary>
  1111. /// Sets the capacity to the actual number of elements in the container.
  1112. /// </summary>
  1113. public void TrimExcess()
  1114. {
  1115. this.ListData().TrimExcess<IntPtr>();
  1116. }
  1117. /// <summary>
  1118. /// Searches for the specified element in list.
  1119. /// </summary>
  1120. /// <param name="value"></param>
  1121. /// <returns>The zero-based index of the first occurrence element if found, otherwise returns -1.</returns>
  1122. public int IndexOf(void* value)
  1123. {
  1124. for (int i = 0; i < Length; ++i)
  1125. {
  1126. if (Ptr[i] == value) return i;
  1127. }
  1128. return -1;
  1129. }
  1130. /// <summary>
  1131. /// Determines whether an element is in the list.
  1132. /// </summary>
  1133. /// <param name="value"></param>
  1134. /// <returns>True, if element is found.</returns>
  1135. public bool Contains(void* value)
  1136. {
  1137. return IndexOf(value) != -1;
  1138. }
  1139. /// <summary>
  1140. /// Adds an element to the list.
  1141. /// </summary>
  1142. /// <param name="value">The value to be added at the end of the list.</param>
  1143. /// <remarks>
  1144. /// If the list has reached its current capacity, internal array won't be resized, and exception will be thrown.
  1145. /// </remarks>
  1146. public void AddNoResize(void* value)
  1147. {
  1148. this.ListData().AddNoResize((IntPtr)value);
  1149. }
  1150. /// <summary>
  1151. /// Adds elements from a buffer to this list.
  1152. /// </summary>
  1153. /// <param name="ptr">A pointer to the buffer.</param>
  1154. /// <param name="length">The number of elements to add to the list.</param>
  1155. /// <remarks>
  1156. /// If the list has reached its current capacity, internal array won't be resized, and exception will be thrown.
  1157. /// </remarks>
  1158. public void AddRangeNoResize(void** ptr, int length)
  1159. {
  1160. this.ListData().AddRangeNoResize<IntPtr>(ptr, length);
  1161. }
  1162. /// <summary>
  1163. /// Adds elements from a list to this list.
  1164. /// </summary>
  1165. /// <param name="list">Other container to copy elements from.</param>
  1166. /// <remarks>
  1167. /// If the list has reached its current capacity, internal array won't be resized, and exception will be thrown.
  1168. /// </remarks>
  1169. public void AddRangeNoResize(UnsafePtrList list)
  1170. {
  1171. this.ListData().AddRangeNoResize<IntPtr>(list.Ptr, list.Length);
  1172. }
  1173. /// <summary>
  1174. /// Adds an element to the list.
  1175. /// </summary>
  1176. /// <param name="value">The struct to be added at the end of the list.</param>
  1177. public void Add(in IntPtr value)
  1178. {
  1179. this.ListData().Add(value);
  1180. }
  1181. /// <summary>
  1182. /// Adds an element to the list.
  1183. /// </summary>
  1184. /// <param name="value">The struct to be added at the end of the list.</param>
  1185. public void Add(void* value)
  1186. {
  1187. this.ListData().Add((IntPtr)value);
  1188. }
  1189. /// <summary>
  1190. /// Adds elements from a buffer to this list.
  1191. /// </summary>
  1192. /// <param name="ptr">A pointer to the buffer.</param>
  1193. /// <param name="length">The number of elements to add to the list.</param>
  1194. public void AddRange(void* ptr, int length)
  1195. {
  1196. this.ListData().AddRange<IntPtr>(ptr, length);
  1197. }
  1198. /// <summary>
  1199. /// Adds the elements of a UnsafePtrList to this list.
  1200. /// </summary>
  1201. /// <param name="list">Other container to copy elements from.</param>
  1202. public void AddRange(UnsafePtrList list)
  1203. {
  1204. this.ListData().AddRange<IntPtr>(list.ListData());
  1205. }
  1206. /// <summary>
  1207. /// Inserts a number of items into a container at a specified zero-based index.
  1208. /// </summary>
  1209. /// <param name="begin">The zero-based index at which the new elements should be inserted.</param>
  1210. /// <param name="end">The zero-based index just after where the elements should be removed.</param>
  1211. /// <exception cref="ArgumentException">Thrown if end argument is less than begin argument.</exception>
  1212. /// <exception cref="ArgumentOutOfRangeException">Thrown if begin or end arguments are not positive or out of bounds.</exception>
  1213. public void InsertRangeWithBeginEnd(int begin, int end)
  1214. {
  1215. this.ListData().InsertRangeWithBeginEnd<IntPtr>(begin, end);
  1216. }
  1217. /// <summary>
  1218. /// Truncates the list by replacing the item at the specified index with the last item in the list. The list
  1219. /// is shortened by one.
  1220. /// </summary>
  1221. /// <param name="index">The index of the item to delete.</param>
  1222. public void RemoveAtSwapBack(int index)
  1223. {
  1224. this.ListData().RemoveAtSwapBack<IntPtr>(index);
  1225. }
  1226. /// <summary>
  1227. /// Truncates the list by replacing the item at the specified index range with the items from the end the list. The list
  1228. /// is shortened by number of elements in range.
  1229. /// </summary>
  1230. /// <param name="begin">The first index of the item to remove.</param>
  1231. /// <param name="end">The index past-the-last item to remove.</param>
  1232. /// <exception cref="ArgumentException">Thrown if end argument is less than begin argument.</exception>
  1233. /// <exception cref="ArgumentOutOfRangeException">Thrown if begin or end arguments are not positive or out of bounds.</exception>
  1234. public void RemoveRangeSwapBackWithBeginEnd(int begin, int end)
  1235. {
  1236. this.ListData().RemoveRangeSwapBackWithBeginEnd<IntPtr>(begin, end);
  1237. }
  1238. /// <summary>
  1239. /// Truncates the list by removing the item at the specified index, and shifting all remaining items to replace removed item. The list
  1240. /// is shortened by one.
  1241. /// </summary>
  1242. /// <param name="index">The index of the item to delete.</param>
  1243. /// <remarks>
  1244. /// This method of removing item is useful only in case when list is ordered and user wants to preserve order
  1245. /// in list after removal In majority of cases is not important and user should use more performant `RemoveAtSwapBack`.
  1246. /// </remarks>
  1247. public void RemoveAt(int index)
  1248. {
  1249. this.ListData().RemoveAt<IntPtr>(index);
  1250. }
  1251. /// <summary>
  1252. /// Truncates the list by removing the items at the specified index range, and shifting all remaining items to replace removed items. The list
  1253. /// is shortened by number of elements in range.
  1254. /// </summary>
  1255. /// <param name="begin">The first index of the item to remove.</param>
  1256. /// <param name="end">The index past-the-last item to remove.</param>
  1257. /// <remarks>
  1258. /// This method of removing item(s) is useful only in case when list is ordered and user wants to preserve order
  1259. /// in list after removal In majority of cases is not important and user should use more performant `RemoveRangeSwapBackWithBeginEnd`.
  1260. /// </remarks>
  1261. /// <exception cref="ArgumentException">Thrown if end argument is less than begin argument.</exception>
  1262. /// <exception cref="ArgumentOutOfRangeException">Thrown if begin or end arguments are not positive or out of bounds.</exception>
  1263. public void RemoveRangeWithBeginEnd(int begin, int end)
  1264. {
  1265. this.ListData().RemoveRangeWithBeginEnd<IntPtr>(begin, end);
  1266. }
  1267. /// <summary>
  1268. /// This method is not implemented. It will throw NotImplementedException if it is used.
  1269. /// </summary>
  1270. /// <remarks>Use Enumerator GetEnumerator() instead.</remarks>
  1271. /// <returns>Throws NotImplementedException.</returns>
  1272. /// <exception cref="NotImplementedException">Method is not implemented.</exception>
  1273. IEnumerator IEnumerable.GetEnumerator()
  1274. {
  1275. throw new NotImplementedException();
  1276. }
  1277. /// <summary>
  1278. /// This method is not implemented. It will throw NotImplementedException if it is used.
  1279. /// </summary>
  1280. /// <remarks>Use Enumerator GetEnumerator() instead.</remarks>
  1281. /// <returns>Throws NotImplementedException.</returns>
  1282. /// <exception cref="NotImplementedException">Method is not implemented.</exception>
  1283. IEnumerator<IntPtr> IEnumerable<IntPtr>.GetEnumerator()
  1284. {
  1285. throw new NotImplementedException();
  1286. }
  1287. /// <summary>
  1288. /// Returns parallel reader instance.
  1289. /// </summary>
  1290. /// <returns>Parallel reader instance.</returns>
  1291. public ParallelReader AsParallelReader()
  1292. {
  1293. return new ParallelReader(Ptr, Length);
  1294. }
  1295. /// <summary>
  1296. /// Implements parallel reader. Use AsParallelReader to obtain it from container.
  1297. /// </summary>
  1298. public unsafe struct ParallelReader
  1299. {
  1300. /// <summary>
  1301. ///
  1302. /// </summary>
  1303. [NativeDisableUnsafePtrRestriction]
  1304. public readonly void** Ptr;
  1305. /// <summary>
  1306. ///
  1307. /// </summary>
  1308. public readonly int Length;
  1309. internal ParallelReader(void** ptr, int length)
  1310. {
  1311. Ptr = ptr;
  1312. Length = length;
  1313. }
  1314. /// <summary>
  1315. ///
  1316. /// </summary>
  1317. /// <param name="value"></param>
  1318. /// <returns></returns>
  1319. public int IndexOf(void* value)
  1320. {
  1321. for (int i = 0; i < Length; ++i)
  1322. {
  1323. if (Ptr[i] == value) return i;
  1324. }
  1325. return -1;
  1326. }
  1327. /// <summary>
  1328. ///
  1329. /// </summary>
  1330. /// <param name="value"></param>
  1331. /// <returns></returns>
  1332. public bool Contains(void* value)
  1333. {
  1334. return IndexOf(value) != -1;
  1335. }
  1336. }
  1337. /// <summary>
  1338. /// Returns parallel writer instance.
  1339. /// </summary>
  1340. /// <returns>Parallel writer instance.</returns>
  1341. public ParallelWriter AsParallelWriter()
  1342. {
  1343. return new ParallelWriter(Ptr, (UnsafeList*)UnsafeUtility.AddressOf(ref this));
  1344. }
  1345. /// <summary>
  1346. ///
  1347. /// </summary>
  1348. public unsafe struct ParallelWriter
  1349. {
  1350. /// <summary>
  1351. ///
  1352. /// </summary>
  1353. [NativeDisableUnsafePtrRestriction]
  1354. public readonly void* Ptr;
  1355. /// <summary>
  1356. ///
  1357. /// </summary>
  1358. [NativeDisableUnsafePtrRestriction]
  1359. public UnsafeList* ListData;
  1360. internal unsafe ParallelWriter(void* ptr, UnsafeList* listData)
  1361. {
  1362. Ptr = ptr;
  1363. ListData = listData;
  1364. }
  1365. /// <summary>
  1366. /// Adds an element to the list.
  1367. /// </summary>
  1368. /// <param name="value">The value to be added at the end of the list.</param>
  1369. /// <remarks>
  1370. /// If the list has reached its current capacity, internal array won't be resized, and exception will be thrown.
  1371. /// </remarks>
  1372. public void AddNoResize(void* value)
  1373. {
  1374. ListData->AddNoResize((IntPtr)value);
  1375. }
  1376. /// <summary>
  1377. /// Adds elements from a buffer to this list.
  1378. /// </summary>
  1379. /// <param name="ptr">A pointer to the buffer.</param>
  1380. /// <param name="length">The number of elements to add to the list.</param>
  1381. /// <remarks>
  1382. /// If the list has reached its current capacity, internal array won't be resized, and exception will be thrown.
  1383. /// </remarks>
  1384. public void AddRangeNoResize(void** ptr, int length)
  1385. {
  1386. ListData->AddRangeNoResize<IntPtr>(ptr, length);
  1387. }
  1388. /// <summary>
  1389. /// Adds elements from a list to this list.
  1390. /// </summary>
  1391. /// <param name="list">Other container to copy elements from.</param>
  1392. /// <remarks>
  1393. /// If the list has reached its current capacity, internal array won't be resized, and exception will be thrown.
  1394. /// </remarks>
  1395. public void AddRangeNoResize(UnsafePtrList list)
  1396. {
  1397. ListData->AddRangeNoResize<IntPtr>(list.Ptr, list.Length);
  1398. }
  1399. }
  1400. }
  1401. internal static class UnsafePtrListExtensions
  1402. {
  1403. public static ref UnsafeList ListData(ref this UnsafePtrList from) => ref UnsafeUtility.As<UnsafePtrList, UnsafeList>(ref from);
  1404. }
  1405. internal sealed class UnsafePtrListDebugView
  1406. {
  1407. UnsafePtrList Data;
  1408. public UnsafePtrListDebugView(UnsafePtrList data)
  1409. {
  1410. Data = data;
  1411. }
  1412. public unsafe IntPtr[] Items
  1413. {
  1414. get
  1415. {
  1416. IntPtr[] result = new IntPtr[Data.Length];
  1417. for (var i = 0; i < result.Length; ++i)
  1418. {
  1419. result[i] = (IntPtr)Data.Ptr[i];
  1420. }
  1421. return result;
  1422. }
  1423. }
  1424. }
  1425. [Obsolete("This storage will no longer be used. (RemovedAfter 2021-06-01)")]
  1426. sealed class WordStorageDebugView
  1427. {
  1428. WordStorage m_wordStorage;
  1429. public WordStorageDebugView(WordStorage wordStorage)
  1430. {
  1431. m_wordStorage = wordStorage;
  1432. }
  1433. public FixedString128Bytes[] Table
  1434. {
  1435. get
  1436. {
  1437. var table = new FixedString128Bytes[m_wordStorage.Entries];
  1438. for (var i = 0; i < m_wordStorage.Entries; ++i)
  1439. m_wordStorage.GetFixedString(i, ref table[i]);
  1440. return table;
  1441. }
  1442. }
  1443. }
  1444. [Obsolete("This storage will no longer be used. (RemovedAfter 2021-06-01)")]
  1445. sealed class WordStorageStatic
  1446. {
  1447. private WordStorageStatic()
  1448. {
  1449. }
  1450. public struct Thing
  1451. {
  1452. public WordStorage Data;
  1453. }
  1454. public static Thing Ref = default;
  1455. }
  1456. /// <summary>
  1457. ///
  1458. /// </summary>
  1459. [Obsolete("This storage will no longer be used. (RemovedAfter 2021-06-01)")]
  1460. [DebuggerTypeProxy(typeof(WordStorageDebugView))]
  1461. public struct WordStorage
  1462. {
  1463. struct Entry
  1464. {
  1465. public int offset;
  1466. public int length;
  1467. }
  1468. NativeArray<byte> buffer; // all the UTF-8 encoded bytes in one place
  1469. NativeArray<Entry> entry; // one offset for each text in "buffer"
  1470. NativeMultiHashMap<int, int> hash; // from string hash to table entry
  1471. int chars; // bytes in buffer allocated so far
  1472. int entries; // number of strings allocated so far
  1473. /// <summary>
  1474. /// For internal use only.
  1475. /// </summary>
  1476. [NotBurstCompatible /* Deprecated */]
  1477. public static ref WordStorage Instance
  1478. {
  1479. get
  1480. {
  1481. Initialize();
  1482. return ref WordStorageStatic.Ref.Data;
  1483. }
  1484. }
  1485. const int kMaxEntries = 16 << 10;
  1486. const int kMaxChars = kMaxEntries * 128;
  1487. /// <summary>
  1488. ///
  1489. /// </summary>
  1490. public const int kMaxCharsPerEntry = 4096;
  1491. /// <summary>
  1492. ///
  1493. /// </summary>
  1494. public int Entries => entries;
  1495. /// <summary>
  1496. ///
  1497. /// </summary>
  1498. [NotBurstCompatible /* Deprecated */]
  1499. public static void Initialize()
  1500. {
  1501. if (WordStorageStatic.Ref.Data.buffer.IsCreated)
  1502. return;
  1503. WordStorageStatic.Ref.Data.buffer = new NativeArray<byte>(kMaxChars, Allocator.Persistent);
  1504. WordStorageStatic.Ref.Data.entry = new NativeArray<Entry>(kMaxEntries, Allocator.Persistent);
  1505. WordStorageStatic.Ref.Data.hash = new NativeMultiHashMap<int, int>(kMaxEntries, Allocator.Persistent);
  1506. Clear();
  1507. #if !UNITY_DOTSRUNTIME
  1508. // Free storage on domain unload, which happens when iterating on the Entities module a lot.
  1509. AppDomain.CurrentDomain.DomainUnload += (_, __) => { Shutdown(); };
  1510. // There is no domain unload in player builds, so we must be sure to shutdown when the process exits.
  1511. AppDomain.CurrentDomain.ProcessExit += (_, __) => { Shutdown(); };
  1512. #endif
  1513. }
  1514. /// <summary>
  1515. ///
  1516. /// </summary>
  1517. [NotBurstCompatible /* Deprecated */]
  1518. public static void Shutdown()
  1519. {
  1520. if (!WordStorageStatic.Ref.Data.buffer.IsCreated)
  1521. return;
  1522. WordStorageStatic.Ref.Data.buffer.Dispose();
  1523. WordStorageStatic.Ref.Data.entry.Dispose();
  1524. WordStorageStatic.Ref.Data.hash.Dispose();
  1525. WordStorageStatic.Ref.Data = default;
  1526. }
  1527. /// <summary>
  1528. ///
  1529. /// </summary>
  1530. [NotBurstCompatible /* Deprecated */]
  1531. public static void Clear()
  1532. {
  1533. Initialize();
  1534. WordStorageStatic.Ref.Data.chars = 0;
  1535. WordStorageStatic.Ref.Data.entries = 0;
  1536. WordStorageStatic.Ref.Data.hash.Clear();
  1537. var temp = new FixedString32Bytes();
  1538. WordStorageStatic.Ref.Data.GetOrCreateIndex(ref temp); // make sure that Index=0 means empty string
  1539. }
  1540. /// <summary>
  1541. ///
  1542. /// </summary>
  1543. [NotBurstCompatible /* Deprecated */]
  1544. public static void Setup()
  1545. {
  1546. Clear();
  1547. }
  1548. /// <summary>
  1549. ///
  1550. /// </summary>
  1551. /// <param name="index"></param>
  1552. /// <param name="temp"></param>
  1553. /// <typeparam name="T"></typeparam>
  1554. public unsafe void GetFixedString<T>(int index, ref T temp)
  1555. where T : IUTF8Bytes, INativeList<byte>
  1556. {
  1557. Assert.IsTrue(index < entries);
  1558. var e = entry[index];
  1559. Assert.IsTrue(e.length <= kMaxCharsPerEntry);
  1560. temp.Length = e.length;
  1561. UnsafeUtility.MemCpy(temp.GetUnsafePtr(), (byte*)buffer.GetUnsafePtr() + e.offset, temp.Length);
  1562. }
  1563. /// <summary>
  1564. ///
  1565. /// </summary>
  1566. /// <param name="h"></param>
  1567. /// <param name="temp"></param>
  1568. /// <typeparam name="T"></typeparam>
  1569. /// <returns></returns>
  1570. public int GetIndexFromHashAndFixedString<T>(int h, ref T temp)
  1571. where T : IUTF8Bytes, INativeList<byte>
  1572. {
  1573. Assert.IsTrue(temp.Length <= kMaxCharsPerEntry); // about one printed page of text
  1574. int itemIndex;
  1575. NativeMultiHashMapIterator<int> iter;
  1576. if (hash.TryGetFirstValue(h, out itemIndex, out iter))
  1577. {
  1578. do
  1579. {
  1580. var e = entry[itemIndex];
  1581. Assert.IsTrue(e.length <= kMaxCharsPerEntry);
  1582. if (e.length == temp.Length)
  1583. {
  1584. int matches;
  1585. for (matches = 0; matches < e.length; ++matches)
  1586. if (temp[matches] != buffer[e.offset + matches])
  1587. break;
  1588. if (matches == temp.Length)
  1589. return itemIndex;
  1590. }
  1591. } while (hash.TryGetNextValue(out itemIndex, ref iter));
  1592. }
  1593. return -1;
  1594. }
  1595. /// <summary>
  1596. ///
  1597. /// </summary>
  1598. /// <param name="value"></param>
  1599. /// <typeparam name="T"></typeparam>
  1600. /// <returns></returns>
  1601. public bool Contains<T>(ref T value)
  1602. where T : IUTF8Bytes, INativeList<byte>
  1603. {
  1604. int h = value.GetHashCode();
  1605. return GetIndexFromHashAndFixedString(h, ref value) != -1;
  1606. }
  1607. /// <summary>
  1608. ///
  1609. /// </summary>
  1610. /// <param name="value"></param>
  1611. /// <returns></returns>
  1612. [NotBurstCompatible /* Deprecated */]
  1613. public unsafe bool Contains(string value)
  1614. {
  1615. FixedString512Bytes temp = value;
  1616. return Contains(ref temp);
  1617. }
  1618. /// <summary>
  1619. ///
  1620. /// </summary>
  1621. /// <param name="value"></param>
  1622. /// <typeparam name="T"></typeparam>
  1623. /// <returns></returns>
  1624. public int GetOrCreateIndex<T>(ref T value)
  1625. where T : IUTF8Bytes, INativeList<byte>
  1626. {
  1627. int h = value.GetHashCode();
  1628. var itemIndex = GetIndexFromHashAndFixedString(h, ref value);
  1629. if (itemIndex != -1)
  1630. return itemIndex;
  1631. Assert.IsTrue(entries < kMaxEntries);
  1632. Assert.IsTrue(chars + value.Length <= kMaxChars);
  1633. var o = chars;
  1634. var l = (ushort)value.Length;
  1635. for (var i = 0; i < l; ++i)
  1636. buffer[chars++] = value[i];
  1637. entry[entries] = new Entry { offset = o, length = l };
  1638. hash.Add(h, entries);
  1639. return entries++;
  1640. }
  1641. }
  1642. /// <summary>
  1643. ///
  1644. /// </summary>
  1645. /// <remarks>
  1646. /// A "Words" is an integer that refers to 4,096 or fewer chars of UTF-16 text in a global storage blob.
  1647. /// Each should refer to *at most* about one printed page of text.
  1648. ///
  1649. /// If you need more text, consider using one Words struct for each printed page's worth.
  1650. ///
  1651. /// Each Words instance that you create is stored in a single, internally-managed WordStorage object,
  1652. /// which can hold up to 16,384 Words entries. Once added, the entries in WordStorage cannot be modified
  1653. /// or removed.
  1654. /// </remarks>
  1655. [Obsolete("This storage will no longer be used. (RemovedAfter 2021-06-01)")]
  1656. public struct Words
  1657. {
  1658. int Index;
  1659. /// <summary>
  1660. ///
  1661. /// </summary>
  1662. /// <param name="value"></param>
  1663. /// <typeparam name="T"></typeparam>
  1664. public void ToFixedString<T>(ref T value)
  1665. where T : IUTF8Bytes, INativeList<byte>
  1666. {
  1667. WordStorage.Instance.GetFixedString(Index, ref value);
  1668. }
  1669. /// <summary>
  1670. ///
  1671. /// </summary>
  1672. /// <returns></returns>
  1673. public override string ToString()
  1674. {
  1675. FixedString512Bytes temp = default;
  1676. ToFixedString(ref temp);
  1677. return temp.ToString();
  1678. }
  1679. /// <summary>
  1680. ///
  1681. /// </summary>
  1682. /// <param name="value"></param>
  1683. /// <typeparam name="T"></typeparam>
  1684. public void SetFixedString<T>(ref T value)
  1685. where T : IUTF8Bytes, INativeList<byte>
  1686. {
  1687. Index = WordStorage.Instance.GetOrCreateIndex(ref value);
  1688. }
  1689. /// <summary>
  1690. ///
  1691. /// </summary>
  1692. /// <param name="value"></param>
  1693. public unsafe void SetString(string value)
  1694. {
  1695. FixedString512Bytes temp = value;
  1696. SetFixedString(ref temp);
  1697. }
  1698. }
  1699. /// <summary>
  1700. ///
  1701. /// </summary>
  1702. /// <remarks>
  1703. /// A "NumberedWords" is a "Words", plus possibly a string of leading zeroes, followed by
  1704. /// possibly a positive integer.
  1705. /// The zeroes and integer aren't stored centrally as a string, they're stored as an int.
  1706. /// Therefore, 1,000,000 items with names from FooBarBazBifBoo000000 to FooBarBazBifBoo999999
  1707. /// Will cost 8MB + a single copy of "FooBarBazBifBoo", instead of ~48MB.
  1708. /// They say that this is a thing, too.
  1709. /// </remarks>
  1710. [Obsolete("This storage will no longer be used. (RemovedAfter 2021-06-01)")]
  1711. public struct NumberedWords
  1712. {
  1713. int Index;
  1714. int Suffix;
  1715. const int kPositiveNumericSuffixShift = 0;
  1716. const int kPositiveNumericSuffixBits = 29;
  1717. const int kMaxPositiveNumericSuffix = (1 << kPositiveNumericSuffixBits) - 1;
  1718. const int kPositiveNumericSuffixMask = (1 << kPositiveNumericSuffixBits) - 1;
  1719. const int kLeadingZeroesShift = 29;
  1720. const int kLeadingZeroesBits = 3;
  1721. const int kMaxLeadingZeroes = (1 << kLeadingZeroesBits) - 1;
  1722. const int kLeadingZeroesMask = (1 << kLeadingZeroesBits) - 1;
  1723. int LeadingZeroes
  1724. {
  1725. get => (Suffix >> kLeadingZeroesShift) & kLeadingZeroesMask;
  1726. set
  1727. {
  1728. Suffix &= ~(kLeadingZeroesMask << kLeadingZeroesShift);
  1729. Suffix |= (value & kLeadingZeroesMask) << kLeadingZeroesShift;
  1730. }
  1731. }
  1732. int PositiveNumericSuffix
  1733. {
  1734. get => (Suffix >> kPositiveNumericSuffixShift) & kPositiveNumericSuffixMask;
  1735. set
  1736. {
  1737. Suffix &= ~(kPositiveNumericSuffixMask << kPositiveNumericSuffixShift);
  1738. Suffix |= (value & kPositiveNumericSuffixMask) << kPositiveNumericSuffixShift;
  1739. }
  1740. }
  1741. bool HasPositiveNumericSuffix => PositiveNumericSuffix != 0;
  1742. [NotBurstCompatible /* Deprecated */]
  1743. string NewString(char c, int count)
  1744. {
  1745. char[] temp = new char[count];
  1746. for (var i = 0; i < count; ++i)
  1747. temp[i] = c;
  1748. return new string(temp, 0, count);
  1749. }
  1750. /// <summary>
  1751. ///
  1752. /// </summary>
  1753. /// <param name="result"></param>
  1754. /// <typeparam name="T"></typeparam>
  1755. /// <returns></returns>
  1756. [NotBurstCompatible /* Deprecated */]
  1757. public int ToFixedString<T>(ref T result)
  1758. where T : IUTF8Bytes, INativeList<byte>
  1759. {
  1760. unsafe
  1761. {
  1762. var positiveNumericSuffix = PositiveNumericSuffix;
  1763. var leadingZeroes = LeadingZeroes;
  1764. WordStorage.Instance.GetFixedString(Index, ref result);
  1765. if(positiveNumericSuffix == 0 && leadingZeroes == 0)
  1766. return 0;
  1767. // print the numeric suffix, if any, backwards, as ASCII, to a little buffer.
  1768. const int maximumDigits = kMaxLeadingZeroes + 10;
  1769. var buffer = stackalloc byte[maximumDigits];
  1770. var firstDigit = maximumDigits;
  1771. while(positiveNumericSuffix > 0)
  1772. {
  1773. buffer[--firstDigit] = (byte)('0' + positiveNumericSuffix % 10);
  1774. positiveNumericSuffix /= 10;
  1775. }
  1776. while(leadingZeroes-- > 0)
  1777. buffer[--firstDigit] = (byte)'0';
  1778. // make space in the output for leading zeroes if any, followed by the positive numeric index if any.
  1779. var dest = result.GetUnsafePtr() + result.Length;
  1780. result.Length += maximumDigits - firstDigit;
  1781. while(firstDigit < maximumDigits)
  1782. *dest++ = buffer[firstDigit++];
  1783. return 0;
  1784. }
  1785. }
  1786. /// <summary>
  1787. ///
  1788. /// </summary>
  1789. /// <returns></returns>
  1790. [NotBurstCompatible /* Deprecated */]
  1791. public override string ToString()
  1792. {
  1793. FixedString512Bytes temp = default;
  1794. ToFixedString(ref temp);
  1795. return temp.ToString();
  1796. }
  1797. bool IsDigit(byte b)
  1798. {
  1799. return b >= '0' && b <= '9';
  1800. }
  1801. /// <summary>
  1802. ///
  1803. /// </summary>
  1804. /// <param name="value"></param>
  1805. /// <typeparam name="T"></typeparam>
  1806. [NotBurstCompatible /* Deprecated */]
  1807. public void SetString<T>(ref T value)
  1808. where T : IUTF8Bytes, INativeList<byte>
  1809. {
  1810. int beginningOfDigits = value.Length;
  1811. // as long as there are digits at the end,
  1812. // look back for more digits.
  1813. while (beginningOfDigits > 0 && IsDigit(value[beginningOfDigits - 1]))
  1814. --beginningOfDigits;
  1815. // as long as the first digit is a zero, it's not the beginning of the positive integer - it's a leading zero.
  1816. var beginningOfPositiveNumericSuffix = beginningOfDigits;
  1817. while (beginningOfPositiveNumericSuffix < value.Length && value[beginningOfPositiveNumericSuffix] == '0')
  1818. ++beginningOfPositiveNumericSuffix;
  1819. // now we know where the leading zeroes begin, and then where the positive integer begins after them.
  1820. // but if there are too many leading zeroes to encode, the excess ones become part of the string.
  1821. var leadingZeroes = beginningOfPositiveNumericSuffix - beginningOfDigits;
  1822. if (leadingZeroes > kMaxLeadingZeroes)
  1823. {
  1824. var excessLeadingZeroes = leadingZeroes - kMaxLeadingZeroes;
  1825. beginningOfDigits += excessLeadingZeroes;
  1826. leadingZeroes -= excessLeadingZeroes;
  1827. }
  1828. // if there is a positive integer after the zeroes, here's where we compute it and store it for later.
  1829. PositiveNumericSuffix = 0;
  1830. {
  1831. int number = 0;
  1832. for (var i = beginningOfPositiveNumericSuffix; i < value.Length; ++i)
  1833. {
  1834. number *= 10;
  1835. number += value[i] - '0';
  1836. }
  1837. // an intrepid user may attempt to encode a positive integer with 20 digits or something.
  1838. // they are rewarded with a string that is encoded wholesale without any optimizations.
  1839. if (number <= kMaxPositiveNumericSuffix)
  1840. PositiveNumericSuffix = number;
  1841. else
  1842. {
  1843. beginningOfDigits = value.Length;
  1844. leadingZeroes = 0; // and your dog Toto, too.
  1845. }
  1846. }
  1847. // set the leading zero count in the Suffix member.
  1848. LeadingZeroes = leadingZeroes;
  1849. // truncate the string, if there were digits at the end that we encoded.
  1850. var truncated = value;
  1851. int length = truncated.Length;
  1852. if (beginningOfDigits != truncated.Length)
  1853. truncated.Length = beginningOfDigits;
  1854. // finally, set the string to its index in the global string blob thing.
  1855. unsafe
  1856. {
  1857. Index = WordStorage.Instance.GetOrCreateIndex(ref truncated);
  1858. }
  1859. }
  1860. /// <summary>
  1861. ///
  1862. /// </summary>
  1863. /// <param name="value"></param>
  1864. [NotBurstCompatible /* Deprecated */]
  1865. public void SetString(string value)
  1866. {
  1867. FixedString512Bytes temp = value;
  1868. SetString(ref temp);
  1869. }
  1870. }
  1871. }