ByteBufferFactory.cs 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. /* Copyright 2010-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.Collections.Generic;
  17. using System.IO;
  18. namespace MongoDB.Bson.IO
  19. {
  20. /// <summary>
  21. /// Represents a factory for IBsonBuffers.
  22. /// </summary>
  23. public static class ByteBufferFactory
  24. {
  25. /// <summary>
  26. /// Creates a buffer of the specified length. Depending on the length, either a SingleChunkBuffer or a MultiChunkBuffer will be created.
  27. /// </summary>
  28. /// <param name="chunkSource">The chunk pool.</param>
  29. /// <param name="minimumCapacity">The minimum capacity.</param>
  30. /// <returns>A buffer with at least the minimum capacity.</returns>
  31. public static IByteBuffer Create(IBsonChunkSource chunkSource, int minimumCapacity)
  32. {
  33. if (chunkSource == null)
  34. {
  35. throw new ArgumentNullException("chunkSource");
  36. }
  37. if (minimumCapacity <= 0)
  38. {
  39. throw new ArgumentOutOfRangeException("minimumCapacity");
  40. }
  41. var capacity = 0;
  42. var chunks = new List<IBsonChunk>();
  43. while (capacity < minimumCapacity)
  44. {
  45. var chunk = chunkSource.GetChunk(minimumCapacity - capacity);
  46. chunks.Add(chunk);
  47. capacity += chunk.Bytes.Count;
  48. }
  49. if (chunks.Count == 1)
  50. {
  51. var chunk = chunks[0];
  52. ByteArrayChunk byteArrayChunk;
  53. if ((byteArrayChunk = chunk as ByteArrayChunk) != null)
  54. {
  55. var segment = byteArrayChunk.Bytes;
  56. if (segment.Offset == 0)
  57. {
  58. return new ByteArrayBuffer(segment.Array, segment.Count, isReadOnly: false);
  59. }
  60. }
  61. return new SingleChunkBuffer(chunk, 0, isReadOnly: false);
  62. }
  63. else
  64. {
  65. return new MultiChunkBuffer(chunks, 0, isReadOnly: false);
  66. }
  67. }
  68. }
  69. }