ArrayHelper.cs 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. using System;
  2. using System.Runtime.CompilerServices;
  3. namespace LitMotion
  4. {
  5. internal static class ArrayHelper
  6. {
  7. const int ArrayMaxSize = 0x7FFFFFC7;
  8. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  9. public static void EnsureCapacity(ref char[] buffer, int minimumCapacity)
  10. {
  11. if (buffer == null)
  12. {
  13. Error.ArgumentNull(nameof(buffer));
  14. }
  15. var current = buffer.Length;
  16. if (minimumCapacity > current)
  17. {
  18. int num = minimumCapacity;
  19. if (num < 256)
  20. {
  21. num = 256;
  22. FastResize(ref buffer, num);
  23. return;
  24. }
  25. if (current == ArrayMaxSize)
  26. {
  27. throw new InvalidOperationException("char[] size reached maximum size of array(0x7FFFFFC7).");
  28. }
  29. var newSize = unchecked(current * 2);
  30. if (newSize < 0)
  31. {
  32. num = ArrayMaxSize;
  33. }
  34. else
  35. {
  36. if (num < newSize)
  37. {
  38. num = newSize;
  39. }
  40. }
  41. FastResize(ref buffer, num);
  42. }
  43. }
  44. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  45. public static void FastResize(ref char[] array, int newSize)
  46. {
  47. if (newSize < 0) throw new ArgumentOutOfRangeException(nameof(newSize));
  48. char[] array2 = array;
  49. if (array2 == null)
  50. {
  51. array = new char[newSize];
  52. return;
  53. }
  54. if (array2.Length != newSize)
  55. {
  56. char[] array3 = new char[newSize];
  57. Buffer.BlockCopy(array2, 0, array3, 0, (array2.Length > newSize) ? newSize : array2.Length);
  58. array = array3;
  59. }
  60. }
  61. }
  62. }