ElementAppendingBsonWriter.cs 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. /* Copyright 2017-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.Linq;
  18. using MongoDB.Bson.Serialization;
  19. using MongoDB.Bson.Serialization.Serializers;
  20. namespace MongoDB.Bson.IO
  21. {
  22. /// <summary>
  23. /// A BsonWriter that appends elements to the end of a document.
  24. /// </summary>
  25. /// <seealso cref="MongoDB.Bson.IO.IBsonWriter" />
  26. internal sealed class ElementAppendingBsonWriter : WrappingBsonWriter
  27. {
  28. // private fields
  29. private int _depth;
  30. private readonly List<BsonElement> _elements;
  31. private readonly Action<BsonWriterSettings> _settingsConfigurator;
  32. // constructors
  33. /// <summary>
  34. /// Initializes a new instance of the <see cref="ElementAppendingBsonWriter" /> class.
  35. /// </summary>
  36. /// <param name="wrapped">The wrapped writer.</param>
  37. /// <param name="elements">The elements to append.</param>
  38. /// <param name="settingsConfigurator">The settings configurator.</param>
  39. public ElementAppendingBsonWriter(
  40. IBsonWriter wrapped,
  41. IEnumerable<BsonElement> elements,
  42. Action<BsonWriterSettings> settingsConfigurator)
  43. : base(wrapped)
  44. {
  45. if (elements == null) { throw new ArgumentNullException(nameof(elements)); }
  46. _elements = elements.ToList();
  47. _settingsConfigurator = settingsConfigurator ?? (s => { });
  48. }
  49. // public methods
  50. /// <inheritdoc />
  51. public override void WriteEndDocument()
  52. {
  53. if (--_depth == 0)
  54. {
  55. Wrapped.PushSettings(_settingsConfigurator);
  56. try
  57. {
  58. var context = BsonSerializationContext.CreateRoot(Wrapped);
  59. foreach (var element in _elements)
  60. {
  61. Wrapped.WriteName(element.Name);
  62. BsonValueSerializer.Instance.Serialize(context, element.Value);
  63. }
  64. }
  65. finally
  66. {
  67. Wrapped.PopSettings();
  68. }
  69. }
  70. base.WriteEndDocument();
  71. }
  72. /// <inheritdoc />
  73. public override void WriteStartDocument()
  74. {
  75. _depth++;
  76. base.WriteStartDocument();
  77. }
  78. }
  79. }