ThreadStaticBuffer.cs 3.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. /* Copyright 2020-present MongoDB Inc.
  2. *
  3. * Licensed under the Apache License, Version 2.0 (the "License");
  4. * you may not use this file except in compliance with the License.
  5. * You may obtain a copy of the License at
  6. *
  7. * http://www.apache.org/licenses/LICENSE-2.0
  8. *
  9. * Unless required by applicable law or agreed to in writing, software
  10. * distributed under the License is distributed on an "AS IS" BASIS,
  11. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. * See the License for the specific language governing permissions and
  13. * limitations under the License.
  14. */
  15. using System;
  16. using System.Threading;
  17. namespace MongoDB.Bson.IO
  18. {
  19. /// <summary>
  20. /// Represents a class that provides reusable buffer per thread.
  21. /// Use this technique ONLY when:
  22. /// 1. Buffer is not shared across multiple threads.
  23. /// 2. No nested methods invocations use the same buffer.
  24. /// Advised to limit the usage scope to a single method.
  25. /// </summary>
  26. internal static class ThreadStaticBuffer
  27. {
  28. public readonly struct RentedBuffer : IDisposable
  29. {
  30. private readonly int _ownerThreadId;
  31. private readonly byte[] _bytes;
  32. public RentedBuffer(int ownerThreadId, byte[] bytes)
  33. {
  34. _ownerThreadId = ownerThreadId;
  35. _bytes = bytes;
  36. }
  37. public void Dispose()
  38. {
  39. if (_ownerThreadId != __threadId)
  40. {
  41. throw new InvalidOperationException("Attempt to return thread static buffer from the wrong thread.");
  42. }
  43. if (!__isBufferRented)
  44. {
  45. throw new InvalidOperationException("Attempt to return a thread static buffer that is not in use.");
  46. }
  47. __isBufferRented = false;
  48. }
  49. public byte[] Bytes => _bytes;
  50. }
  51. private const int MinSize = 256;
  52. private const int MaxSize = 16384;
  53. private const int MaxAllocationSize = 1024 * 1024 * 1024; // 1GB
  54. // private static fields
  55. [ThreadStatic]
  56. private static byte[] __buffer;
  57. [ThreadStatic]
  58. private static bool __isBufferRented;
  59. [ThreadStatic]
  60. private static int __threadId;
  61. public static RentedBuffer RentBuffer(int size)
  62. {
  63. if (__isBufferRented)
  64. {
  65. throw new InvalidOperationException("Thread static buffer is already in use.");
  66. }
  67. if (size <= 0 || size > MaxAllocationSize)
  68. {
  69. throw new ArgumentOutOfRangeException(nameof(size), size, $"Valid buffer size range is [1..{MaxAllocationSize}] bytes.");
  70. }
  71. __isBufferRented = true;
  72. if (__threadId == default)
  73. {
  74. __threadId = Thread.CurrentThread.ManagedThreadId;
  75. }
  76. if (size > MaxSize)
  77. {
  78. return new RentedBuffer(__threadId, new byte[size]);
  79. }
  80. if (__buffer == null || __buffer.Length < size)
  81. {
  82. var newSize = size <= MinSize ? MinSize : PowerOf2.RoundUpToPowerOf2(size);
  83. __buffer = new byte[newSize];
  84. }
  85. return new RentedBuffer(__threadId, __buffer);
  86. }
  87. }
  88. }