BufferPool.cs 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. using System.Threading;
  5. using BestHTTP.PlatformSupport.Threading;
  6. #if NET_STANDARD_2_0 || NETFX_CORE
  7. using System.Runtime.CompilerServices;
  8. #endif
  9. namespace BestHTTP.PlatformSupport.Memory
  10. {
  11. [BestHTTP.PlatformSupport.IL2CPP.Il2CppEagerStaticClassConstructionAttribute]
  12. public struct BufferSegment
  13. {
  14. private const int ToStringMaxDumpLength = 128;
  15. public static readonly BufferSegment Empty = new BufferSegment(null, 0, 0);
  16. public readonly byte[] Data;
  17. public readonly int Offset;
  18. public readonly int Count;
  19. public BufferSegment(byte[] data, int offset, int count)
  20. {
  21. this.Data = data;
  22. this.Offset = offset;
  23. this.Count = count;
  24. }
  25. [BestHTTP.PlatformSupport.IL2CPP.Il2CppSetOption(BestHTTP.PlatformSupport.IL2CPP.Option.NullChecks, false)]
  26. [BestHTTP.PlatformSupport.IL2CPP.Il2CppSetOption(BestHTTP.PlatformSupport.IL2CPP.Option.ArrayBoundsChecks, false)]
  27. [BestHTTP.PlatformSupport.IL2CPP.Il2CppSetOption(BestHTTP.PlatformSupport.IL2CPP.Option.DivideByZeroChecks, false)]
  28. public override bool Equals(object obj)
  29. {
  30. if (obj == null || !(obj is BufferSegment))
  31. return false;
  32. return Equals((BufferSegment)obj);
  33. }
  34. [BestHTTP.PlatformSupport.IL2CPP.Il2CppSetOption(BestHTTP.PlatformSupport.IL2CPP.Option.NullChecks, false)]
  35. [BestHTTP.PlatformSupport.IL2CPP.Il2CppSetOption(BestHTTP.PlatformSupport.IL2CPP.Option.ArrayBoundsChecks, false)]
  36. [BestHTTP.PlatformSupport.IL2CPP.Il2CppSetOption(BestHTTP.PlatformSupport.IL2CPP.Option.DivideByZeroChecks, false)]
  37. public bool Equals(BufferSegment other)
  38. {
  39. return this.Data == other.Data &&
  40. this.Offset == other.Offset &&
  41. this.Count == other.Count;
  42. }
  43. [BestHTTP.PlatformSupport.IL2CPP.Il2CppSetOption(BestHTTP.PlatformSupport.IL2CPP.Option.NullChecks, false)]
  44. [BestHTTP.PlatformSupport.IL2CPP.Il2CppSetOption(BestHTTP.PlatformSupport.IL2CPP.Option.ArrayBoundsChecks, false)]
  45. [BestHTTP.PlatformSupport.IL2CPP.Il2CppSetOption(BestHTTP.PlatformSupport.IL2CPP.Option.DivideByZeroChecks, false)]
  46. public override int GetHashCode()
  47. {
  48. return (this.Data != null ? this.Data.GetHashCode() : 0) * 21 + this.Offset + this.Count;
  49. }
  50. [BestHTTP.PlatformSupport.IL2CPP.Il2CppSetOption(BestHTTP.PlatformSupport.IL2CPP.Option.NullChecks, false)]
  51. [BestHTTP.PlatformSupport.IL2CPP.Il2CppSetOption(BestHTTP.PlatformSupport.IL2CPP.Option.ArrayBoundsChecks, false)]
  52. [BestHTTP.PlatformSupport.IL2CPP.Il2CppSetOption(BestHTTP.PlatformSupport.IL2CPP.Option.DivideByZeroChecks, false)]
  53. public static bool operator ==(BufferSegment left, BufferSegment right)
  54. {
  55. return left.Equals(right);
  56. }
  57. [BestHTTP.PlatformSupport.IL2CPP.Il2CppSetOption(BestHTTP.PlatformSupport.IL2CPP.Option.NullChecks, false)]
  58. [BestHTTP.PlatformSupport.IL2CPP.Il2CppSetOption(BestHTTP.PlatformSupport.IL2CPP.Option.ArrayBoundsChecks, false)]
  59. [BestHTTP.PlatformSupport.IL2CPP.Il2CppSetOption(BestHTTP.PlatformSupport.IL2CPP.Option.DivideByZeroChecks, false)]
  60. public static bool operator !=(BufferSegment left, BufferSegment right)
  61. {
  62. return !left.Equals(right);
  63. }
  64. [BestHTTP.PlatformSupport.IL2CPP.Il2CppSetOption(BestHTTP.PlatformSupport.IL2CPP.Option.NullChecks, false)]
  65. [BestHTTP.PlatformSupport.IL2CPP.Il2CppSetOption(BestHTTP.PlatformSupport.IL2CPP.Option.ArrayBoundsChecks, false)]
  66. [BestHTTP.PlatformSupport.IL2CPP.Il2CppSetOption(BestHTTP.PlatformSupport.IL2CPP.Option.DivideByZeroChecks, false)]
  67. public override string ToString()
  68. {
  69. var sb = new System.Text.StringBuilder("[BufferSegment ");
  70. sb.AppendFormat("Offset: {0} ", this.Offset);
  71. sb.AppendFormat("Count: {0} ", this.Count);
  72. sb.Append("Data: [");
  73. if (this.Count > 0)
  74. {
  75. if (this.Count <= ToStringMaxDumpLength)
  76. {
  77. sb.AppendFormat("{0:X2}", this.Data[this.Offset]);
  78. for (int i = 1; i < this.Count; ++i)
  79. sb.AppendFormat(", {0:X2}", this.Data[this.Offset + i]);
  80. }
  81. else
  82. sb.Append("...");
  83. }
  84. sb.Append("]]");
  85. return sb.ToString();
  86. }
  87. }
  88. [BestHTTP.PlatformSupport.IL2CPP.Il2CppEagerStaticClassConstructionAttribute]
  89. public struct PooledBuffer : IDisposable
  90. {
  91. public byte[] Data;
  92. public int Length;
  93. public void Dispose()
  94. {
  95. if (this.Data != null)
  96. BufferPool.Release(this.Data);
  97. this.Data = null;
  98. }
  99. }
  100. /// <summary>
  101. /// Private data struct that contains the size <-> byte arrays mapping.
  102. /// </summary>
  103. [BestHTTP.PlatformSupport.IL2CPP.Il2CppEagerStaticClassConstructionAttribute]
  104. struct BufferStore
  105. {
  106. /// <summary>
  107. /// Size/length of the arrays stored in the buffers.
  108. /// </summary>
  109. public readonly long Size;
  110. /// <summary>
  111. ///
  112. /// </summary>
  113. public List<BufferDesc> buffers;
  114. public BufferStore(long size)
  115. {
  116. this.Size = size;
  117. this.buffers = new List<BufferDesc>();
  118. }
  119. /// <summary>
  120. /// Create a new store with its first byte[] to store.
  121. /// </summary>
  122. public BufferStore(long size, byte[] buffer)
  123. : this(size)
  124. {
  125. this.buffers.Add(new BufferDesc(buffer));
  126. }
  127. public override string ToString()
  128. {
  129. return string.Format("[BufferStore Size: {0:N0}, Buffers: {1}]", this.Size, this.buffers.Count);
  130. }
  131. }
  132. [BestHTTP.PlatformSupport.IL2CPP.Il2CppEagerStaticClassConstructionAttribute]
  133. struct BufferDesc
  134. {
  135. public static readonly BufferDesc Empty = new BufferDesc(null);
  136. /// <summary>
  137. /// The actual reference to the stored byte array.
  138. /// </summary>
  139. public byte[] buffer;
  140. /// <summary>
  141. /// When the buffer is put back to the pool. Based on this value the pool will calculate the age of the buffer.
  142. /// </summary>
  143. public DateTime released;
  144. #if UNITY_EDITOR
  145. public string stackTrace;
  146. #endif
  147. public BufferDesc(byte[] buff)
  148. {
  149. this.buffer = buff;
  150. this.released = DateTime.UtcNow;
  151. #if UNITY_EDITOR
  152. if (BufferPool.EnableDebugStackTraceCollection)
  153. this.stackTrace = ProcessStackTrace(System.Environment.StackTrace);
  154. else
  155. this.stackTrace = string.Empty;
  156. #endif
  157. }
  158. #if UNITY_EDITOR
  159. private static string ProcessStackTrace(string stackTrace)
  160. {
  161. if (string.IsNullOrEmpty(stackTrace))
  162. return null;
  163. var lines = stackTrace.Split('\n');
  164. StringBuilder sb = new StringBuilder(lines.Length - 3);
  165. // skip top 4 lines that would show the logger.
  166. for (int i = 3; i < lines.Length; ++i)
  167. sb.Append(lines[i].Replace("BestHTTP.", ""));
  168. return sb.ToString();
  169. }
  170. #endif
  171. public override string ToString()
  172. {
  173. #if UNITY_EDITOR
  174. if (BufferPool.EnableDebugStackTraceCollection)
  175. return string.Format("[BufferDesc Size: {0}, Released: {1}, Released StackTrace: {2}]", this.buffer.Length, DateTime.UtcNow - this.released, this.stackTrace);
  176. else
  177. return string.Format("[BufferDesc Size: {0}, Released: {1}]", this.buffer.Length, DateTime.UtcNow - this.released);
  178. #else
  179. return string.Format("[BufferDesc Size: {0}, Released: {1}]", this.buffer.Length, DateTime.UtcNow - this.released);
  180. #endif
  181. }
  182. }
  183. [BestHTTP.PlatformSupport.IL2CPP.Il2CppSetOption(BestHTTP.PlatformSupport.IL2CPP.Option.NullChecks, false)]
  184. [BestHTTP.PlatformSupport.IL2CPP.Il2CppSetOption(BestHTTP.PlatformSupport.IL2CPP.Option.ArrayBoundsChecks, false)]
  185. [BestHTTP.PlatformSupport.IL2CPP.Il2CppSetOption(BestHTTP.PlatformSupport.IL2CPP.Option.DivideByZeroChecks, false)]
  186. [BestHTTP.PlatformSupport.IL2CPP.Il2CppEagerStaticClassConstructionAttribute]
  187. public static class BufferPool
  188. {
  189. public static readonly byte[] NoData = new byte[0];
  190. /// <summary>
  191. /// Setting this property to false the pooling mechanism can be disabled.
  192. /// </summary>
  193. public static bool IsEnabled {
  194. get { return _isEnabled; }
  195. set
  196. {
  197. _isEnabled = value;
  198. // When set to non-enabled remove all stored entries
  199. if (!_isEnabled)
  200. Clear();
  201. }
  202. }
  203. private static volatile bool _isEnabled = true;
  204. /// <summary>
  205. /// Buffer entries that released back to the pool and older than this value are moved when next maintenance is triggered.
  206. /// </summary>
  207. public static TimeSpan RemoveOlderThan = TimeSpan.FromSeconds(30);
  208. /// <summary>
  209. /// How often pool maintenance must run.
  210. /// </summary>
  211. public static TimeSpan RunMaintenanceEvery = TimeSpan.FromSeconds(10);
  212. /// <summary>
  213. /// Minimum buffer size that the plugin will allocate when the requested size is smaller than this value, and canBeLarger is set to true.
  214. /// </summary>
  215. public static long MinBufferSize = 32;
  216. /// <summary>
  217. /// Maximum size of a buffer that the plugin will store.
  218. /// </summary>
  219. public static long MaxBufferSize = long.MaxValue;
  220. /// <summary>
  221. /// Maximum accumulated size of the stored buffers.
  222. /// </summary>
  223. public static long MaxPoolSize = 10 * 1024 * 1024;
  224. /// <summary>
  225. /// Whether to remove empty buffer stores from the free list.
  226. /// </summary>
  227. public static bool RemoveEmptyLists = false;
  228. /// <summary>
  229. /// If it set to true and a byte[] is released more than once it will log out an error.
  230. /// </summary>
  231. public static bool IsDoubleReleaseCheckEnabled = false;
  232. #if UNITY_EDITOR
  233. /// <summary>
  234. /// When set to true, the plugin collects Get and Release stack trace informations.
  235. /// </summary>
  236. public static bool EnableDebugStackTraceCollection = false;
  237. #endif
  238. // It must be sorted by buffer size!
  239. private readonly static List<BufferStore> FreeBuffers = new List<BufferStore>();
  240. private static DateTime lastMaintenance = DateTime.MinValue;
  241. // Statistics
  242. private static long PoolSize = 0;
  243. private static long GetBuffers = 0;
  244. private static long ReleaseBuffers = 0;
  245. private readonly static System.Text.StringBuilder statiscticsBuilder = new System.Text.StringBuilder();
  246. private readonly static ReaderWriterLockSlim rwLock = new ReaderWriterLockSlim(LockRecursionPolicy.NoRecursion);
  247. #if UNITY_EDITOR
  248. private readonly static Dictionary<string, int> getStackStats = new Dictionary<string, int>();
  249. private readonly static Dictionary<string, int> releaseStackStats = new Dictionary<string, int>();
  250. #endif
  251. static BufferPool()
  252. {
  253. #if UNITY_EDITOR
  254. IsDoubleReleaseCheckEnabled = true;
  255. #else
  256. IsDoubleReleaseCheckEnabled = false;
  257. #endif
  258. }
  259. /// <summary>
  260. /// Get byte[] from the pool. If canBeLarge is true, the returned buffer might be larger than the requested size.
  261. /// </summary>
  262. public static byte[] Get(long size, bool canBeLarger)
  263. {
  264. if (!_isEnabled)
  265. return new byte[size];
  266. // Return a fix reference for 0 length requests. Any resize call (even Array.Resize) creates a new reference
  267. // so we are safe to expose it to multiple callers.
  268. if (size == 0)
  269. return BufferPool.NoData;
  270. #if UNITY_EDITOR
  271. if (EnableDebugStackTraceCollection)
  272. {
  273. lock (getStackStats)
  274. {
  275. string stack = ProcessStackTrace(System.Environment.StackTrace);
  276. int value;
  277. if (!getStackStats.TryGetValue(stack, out value))
  278. getStackStats.Add(stack, 1);
  279. else
  280. getStackStats[stack] = ++value;
  281. }
  282. }
  283. #endif
  284. if (canBeLarger)
  285. {
  286. if (size < MinBufferSize)
  287. size = MinBufferSize;
  288. else if (!IsPowerOfTwo(size))
  289. size = NextPowerOf2(size);
  290. }
  291. if (FreeBuffers.Count == 0)
  292. return new byte[size];
  293. BufferDesc bufferDesc = FindFreeBuffer(size, canBeLarger);
  294. if (bufferDesc.buffer == null)
  295. return new byte[size];
  296. else
  297. Interlocked.Increment(ref GetBuffers);
  298. Interlocked.Add(ref PoolSize, -bufferDesc.buffer.Length);
  299. return bufferDesc.buffer;
  300. }
  301. /// <summary>
  302. /// Release back a BufferSegment's data to the pool.
  303. /// </summary>
  304. /// <param name="segment"></param>
  305. public static void Release(BufferSegment segment)
  306. {
  307. Release(segment.Data);
  308. }
  309. /// <summary>
  310. /// Release back a byte array to the pool.
  311. /// </summary>
  312. public static void Release(byte[] buffer)
  313. {
  314. if (!_isEnabled || buffer == null)
  315. return;
  316. #if UNITY_EDITOR
  317. if (EnableDebugStackTraceCollection)
  318. {
  319. lock (releaseStackStats)
  320. {
  321. string stack = ProcessStackTrace(System.Environment.StackTrace);
  322. int value;
  323. if (!releaseStackStats.TryGetValue(stack, out value))
  324. releaseStackStats.Add(stack, 1);
  325. else
  326. releaseStackStats[stack] = ++value;
  327. }
  328. }
  329. #endif
  330. int size = buffer.Length;
  331. if (size == 0 || size > MaxBufferSize)
  332. return;
  333. using (new WriteLock(rwLock))
  334. {
  335. if (PoolSize + size > MaxPoolSize)
  336. return;
  337. PoolSize += size;
  338. ReleaseBuffers++;
  339. AddFreeBuffer(buffer);
  340. }
  341. }
  342. /// <summary>
  343. /// Resize a byte array. It will release the old one to the pool, and the new one is from the pool too.
  344. /// </summary>
  345. public static byte[] Resize(ref byte[] buffer, int newSize, bool canBeLarger, bool clear)
  346. {
  347. if (!_isEnabled)
  348. {
  349. Array.Resize<byte>(ref buffer, newSize);
  350. return buffer;
  351. }
  352. byte[] newBuf = BufferPool.Get(newSize, canBeLarger);
  353. if (buffer != null)
  354. {
  355. if (!clear)
  356. Array.Copy(buffer, 0, newBuf, 0, Math.Min(newBuf.Length, buffer.Length));
  357. BufferPool.Release(buffer);
  358. }
  359. if (clear)
  360. Array.Clear(newBuf, 0, newSize);
  361. return buffer = newBuf;
  362. }
  363. /// <summary>
  364. /// Get textual statistics about the buffer pool.
  365. /// </summary>
  366. public static string GetStatistics(bool showEmptyBuffers = true)
  367. {
  368. using (new ReadLock(rwLock))
  369. {
  370. statiscticsBuilder.Length = 0;
  371. statiscticsBuilder.AppendFormat("Pooled array reused count: {0:N0}\n", GetBuffers);
  372. statiscticsBuilder.AppendFormat("Release call count: {0:N0}\n", ReleaseBuffers);
  373. statiscticsBuilder.AppendFormat("PoolSize: {0:N0}\n", PoolSize);
  374. statiscticsBuilder.AppendFormat("Buffers: {0}\n", FreeBuffers.Count);
  375. for (int i = 0; i < FreeBuffers.Count; ++i)
  376. {
  377. BufferStore store = FreeBuffers[i];
  378. List<BufferDesc> buffers = store.buffers;
  379. if (showEmptyBuffers || buffers.Count > 0)
  380. statiscticsBuilder.AppendFormat("- Size: {0:N0} Count: {1:N0}\n", store.Size, buffers.Count);
  381. }
  382. #if UNITY_EDITOR
  383. if (EnableDebugStackTraceCollection)
  384. {
  385. lock (getStackStats)
  386. {
  387. int sum = 0;
  388. foreach (var kvp in getStackStats)
  389. sum += kvp.Value;
  390. statiscticsBuilder.AppendFormat("Get stacks: {0:N0}\n", sum);
  391. foreach (var kvp in getStackStats)
  392. {
  393. statiscticsBuilder.AppendFormat("- {0:N0}: {1}\n", kvp.Value, kvp.Key);
  394. }
  395. }
  396. lock (releaseStackStats)
  397. {
  398. int sum = 0;
  399. foreach (var kvp in releaseStackStats)
  400. sum += kvp.Value;
  401. statiscticsBuilder.AppendFormat("Release stacks: {0:N0}\n", sum);
  402. foreach (var kvp in releaseStackStats)
  403. {
  404. statiscticsBuilder.AppendFormat("- {0:N0}: {1}\n", kvp.Value, kvp.Key);
  405. }
  406. }
  407. }
  408. #endif
  409. return statiscticsBuilder.ToString();
  410. }
  411. }
  412. /// <summary>
  413. /// Remove all stored entries instantly.
  414. /// </summary>
  415. public static void Clear()
  416. {
  417. using (new WriteLock(rwLock))
  418. {
  419. FreeBuffers.Clear();
  420. PoolSize = 0;
  421. }
  422. }
  423. /// <summary>
  424. /// Internal function called by the plugin to remove old, non-used buffers.
  425. /// </summary>
  426. internal static void Maintain()
  427. {
  428. DateTime now = DateTime.UtcNow;
  429. if (!_isEnabled || lastMaintenance + RunMaintenanceEvery > now)
  430. return;
  431. lastMaintenance = now;
  432. //if (HTTPManager.Logger.Level == Logger.Loglevels.All)
  433. // HTTPManager.Logger.Information("BufferPool", "Before Maintain: " + GetStatistics());
  434. DateTime olderThan = now - RemoveOlderThan;
  435. using (new WriteLock(rwLock))
  436. {
  437. for (int i = 0; i < FreeBuffers.Count; ++i)
  438. {
  439. BufferStore store = FreeBuffers[i];
  440. List<BufferDesc> buffers = store.buffers;
  441. for (int cv = buffers.Count - 1; cv >= 0; cv--)
  442. {
  443. BufferDesc desc = buffers[cv];
  444. if (desc.released < olderThan)
  445. {
  446. // buffers stores available buffers ascending by age. So, when we find an old enough, we can
  447. // delete all entries in the [0..cv] range.
  448. int removeCount = cv + 1;
  449. buffers.RemoveRange(0, removeCount);
  450. PoolSize -= (int)(removeCount * store.Size);
  451. break;
  452. }
  453. }
  454. if (RemoveEmptyLists && buffers.Count == 0)
  455. FreeBuffers.RemoveAt(i--);
  456. }
  457. }
  458. //if (HTTPManager.Logger.Level == Logger.Loglevels.All)
  459. // HTTPManager.Logger.Information("BufferPool", "After Maintain: " + GetStatistics());
  460. }
  461. #region Private helper functions
  462. #if NET_STANDARD_2_0 || NETFX_CORE
  463. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  464. #endif
  465. private static bool IsPowerOfTwo(long x)
  466. {
  467. return (x & (x - 1)) == 0;
  468. }
  469. #if NET_STANDARD_2_0 || NETFX_CORE
  470. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  471. #endif
  472. private static long NextPowerOf2(long x)
  473. {
  474. long pow = 1;
  475. while (pow <= x)
  476. pow *= 2;
  477. return pow;
  478. }
  479. #if NET_STANDARD_2_0 || NETFX_CORE
  480. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  481. #endif
  482. private static BufferDesc FindFreeBuffer(long size, bool canBeLarger)
  483. {
  484. // Previously it was an upgradable read lock, and later a write lock around store.buffers.RemoveAt.
  485. // However, checking store.buffers.Count in the if statement, and then get the last buffer and finally write lock the RemoveAt call
  486. // has plenty of time for race conditions.
  487. // Another thread could change store.buffers after checking count and getting the last element and before the write lock,
  488. // so in theory we could return with an element and remove another one from the buffers list.
  489. // A new FindFreeBuffer call could return it again causing malformed data and/or releasing it could duplicate it in the store.
  490. // I tried to reproduce both issues (malformed data, duble entries) with a test where creating growin number of threads getting buffers writing to them, check the buffers and finally release them
  491. // would fail _only_ if i used a plain Enter/Exit ReadLock pair, or no locking at all.
  492. // But, because there's quite a few different platforms and unity's implementation can be different too, switching from an upgradable lock to a more stricter write lock seems safer.
  493. //
  494. // An interesting read can be found here: https://stackoverflow.com/questions/21411018/readerwriterlockslim-enterupgradeablereadlock-always-a-deadlock
  495. using (new WriteLock(rwLock))
  496. {
  497. for (int i = 0; i < FreeBuffers.Count; ++i)
  498. {
  499. BufferStore store = FreeBuffers[i];
  500. if (store.buffers.Count > 0 && (store.Size == size || (canBeLarger && store.Size > size)))
  501. {
  502. // Getting the last one has two desired effect:
  503. // 1.) RemoveAt should be quicker as it don't have to move all the remaining entries
  504. // 2.) Old, non-used buffers will age. Getting a buffer and putting it back will not keep buffers fresh.
  505. BufferDesc lastFree = store.buffers[store.buffers.Count - 1];
  506. store.buffers.RemoveAt(store.buffers.Count - 1);
  507. return lastFree;
  508. }
  509. }
  510. }
  511. return BufferDesc.Empty;
  512. }
  513. #if NET_STANDARD_2_0 || NETFX_CORE
  514. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  515. #endif
  516. private static void AddFreeBuffer(byte[] buffer)
  517. {
  518. int bufferLength = buffer.Length;
  519. for (int i = 0; i < FreeBuffers.Count; ++i)
  520. {
  521. BufferStore store = FreeBuffers[i];
  522. if (store.Size == bufferLength)
  523. {
  524. // We highly assume here that every buffer will be released only once.
  525. // Checking for double-release would mean that we have to do another O(n) operation, where n is the
  526. // count of the store's elements.
  527. if (IsDoubleReleaseCheckEnabled)
  528. for (int cv = 0; cv < store.buffers.Count; ++cv)
  529. {
  530. var entry = store.buffers[cv];
  531. if (System.Object.ReferenceEquals(entry.buffer, buffer))
  532. {
  533. HTTPManager.Logger.Error("BufferPool", string.Format("Buffer ({0}) already added to the pool!", entry.ToString()));
  534. return;
  535. }
  536. }
  537. store.buffers.Add(new BufferDesc(buffer));
  538. return;
  539. }
  540. if (store.Size > bufferLength)
  541. {
  542. FreeBuffers.Insert(i, new BufferStore(bufferLength, buffer));
  543. return;
  544. }
  545. }
  546. // When we reach this point, there's no same sized or larger BufferStore present, so we have to add a new one
  547. // to the end of our list.
  548. FreeBuffers.Add(new BufferStore(bufferLength, buffer));
  549. }
  550. #if UNITY_EDITOR
  551. private static string ProcessStackTrace(string stackTrace)
  552. {
  553. if (string.IsNullOrEmpty(stackTrace))
  554. return string.Empty;
  555. var lines = stackTrace.Split('\n');
  556. StringBuilder sb = new StringBuilder(lines.Length);
  557. // skip top 4 lines that would show the logger.
  558. for (int i = 2; i < Math.Min(5, lines.Length); ++i)
  559. sb.Append(lines[i].Replace("BestHTTP.", ""));
  560. return sb.ToString();
  561. }
  562. #endif
  563. #endregion
  564. }
  565. }