BsonBinaryWriter.cs 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752
  1. /* Copyright 2010-2014 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. using System.Text;
  19. namespace MongoDB.Bson.IO
  20. {
  21. /// <summary>
  22. /// Represents a BSON writer to a BSON Stream.
  23. /// </summary>
  24. public class BsonBinaryWriter : BsonWriter
  25. {
  26. // private static fields
  27. private static readonly UTF8Encoding __strictUtf8Encoding = new UTF8Encoding(false, true);
  28. // private fields
  29. private Stream _stream; // can be null if we're only writing to the buffer
  30. private BsonBuffer _buffer;
  31. private bool _disposeBuffer;
  32. private BsonBinaryWriterSettings _binaryWriterSettings; // same value as in base class just declared as derived class
  33. private Stack<int> _maxDocumentSizeStack = new Stack<int>();
  34. private BsonBinaryWriterContext _context;
  35. // constructors
  36. /// <summary>
  37. /// Initializes a new instance of the BsonBinaryWriter class.
  38. /// </summary>
  39. /// <param name="stream">A stream.</param>
  40. /// <param name="buffer">A BsonBuffer.</param>
  41. /// <param name="settings">Optional BsonBinaryWriter settings.</param>
  42. public BsonBinaryWriter(Stream stream, BsonBuffer buffer, BsonBinaryWriterSettings settings)
  43. : this(buffer ?? new BsonBuffer(), buffer == null, settings)
  44. {
  45. _stream = stream;
  46. }
  47. /// <summary>
  48. /// Initializes a new instance of the BsonBinaryWriter class.
  49. /// </summary>
  50. /// <param name="buffer">A BsonBuffer.</param>
  51. /// <param name="disposeBuffer">if set to <c>true</c> this BsonBinaryReader will own the buffer and when Dispose is called the buffer will be Disposed also.</param>
  52. /// <param name="settings">Optional BsonBinaryWriter settings.</param>
  53. /// <exception cref="System.ArgumentNullException">
  54. /// encoder
  55. /// or
  56. /// settings
  57. /// </exception>
  58. public BsonBinaryWriter(BsonBuffer buffer, bool disposeBuffer, BsonBinaryWriterSettings settings)
  59. : base(settings)
  60. {
  61. if (buffer == null)
  62. {
  63. throw new ArgumentNullException("encoder");
  64. }
  65. _buffer = buffer;
  66. _disposeBuffer = disposeBuffer;
  67. _binaryWriterSettings = settings; // already frozen by base class
  68. _maxDocumentSizeStack.Push(_binaryWriterSettings.MaxDocumentSize);
  69. _context = null;
  70. State = BsonWriterState.Initial;
  71. }
  72. // public properties
  73. /// <summary>
  74. /// Gets the writer's BsonBuffer.
  75. /// </summary>
  76. public BsonBuffer Buffer
  77. {
  78. get { return _buffer; }
  79. }
  80. // public methods
  81. /// <summary>
  82. /// Closes the writer.
  83. /// </summary>
  84. public override void Close()
  85. {
  86. // Close can be called on Disposed objects
  87. if (State != BsonWriterState.Closed)
  88. {
  89. if (State == BsonWriterState.Done)
  90. {
  91. Flush();
  92. }
  93. if (_stream != null && _binaryWriterSettings.CloseOutput)
  94. {
  95. _stream.Close();
  96. }
  97. _context = null;
  98. State = BsonWriterState.Closed;
  99. }
  100. }
  101. /// <summary>
  102. /// Flushes any pending data to the output destination.
  103. /// </summary>
  104. public override void Flush()
  105. {
  106. if (Disposed) { throw new ObjectDisposedException("BsonBinaryWriter"); }
  107. if (State == BsonWriterState.Closed)
  108. {
  109. throw new InvalidOperationException("Flush called on closed BsonWriter.");
  110. }
  111. if (State != BsonWriterState.Done)
  112. {
  113. throw new InvalidOperationException("Flush called before BsonBinaryWriter was finished writing to buffer.");
  114. }
  115. if (_stream != null)
  116. {
  117. _buffer.WriteTo(_stream);
  118. _stream.Flush();
  119. _buffer.Clear(); // only clear the buffer if we have written it to a stream
  120. }
  121. }
  122. /// <summary>
  123. /// Pops the max document size stack, restoring the previous max document size.
  124. /// </summary>
  125. public void PopMaxDocumentSize()
  126. {
  127. _maxDocumentSizeStack.Pop();
  128. }
  129. /// <summary>
  130. /// Pushes a new max document size onto the max document size stack.
  131. /// </summary>
  132. /// <param name="maxDocumentSize">The maximum size of the document.</param>
  133. public void PushMaxDocumentSize(int maxDocumentSize)
  134. {
  135. _maxDocumentSizeStack.Push(Math.Min(maxDocumentSize, _maxDocumentSizeStack.Peek()));
  136. }
  137. #pragma warning disable 618 // about obsolete BsonBinarySubType.OldBinary
  138. /// <summary>
  139. /// Writes BSON binary data to the writer.
  140. /// </summary>
  141. /// <param name="binaryData">The binary data.</param>
  142. public override void WriteBinaryData(BsonBinaryData binaryData)
  143. {
  144. if (Disposed) { throw new ObjectDisposedException("BsonBinaryWriter"); }
  145. if (State != BsonWriterState.Value)
  146. {
  147. ThrowInvalidState("WriteBinaryData", BsonWriterState.Value);
  148. }
  149. var bytes = binaryData.Bytes;
  150. var subType = binaryData.SubType;
  151. var guidRepresentation = binaryData.GuidRepresentation;
  152. switch (subType)
  153. {
  154. case BsonBinarySubType.OldBinary:
  155. if (_binaryWriterSettings.FixOldBinarySubTypeOnOutput)
  156. {
  157. subType = BsonBinarySubType.Binary; // replace obsolete OldBinary with new Binary sub type
  158. }
  159. break;
  160. case BsonBinarySubType.UuidLegacy:
  161. case BsonBinarySubType.UuidStandard:
  162. if (_binaryWriterSettings.GuidRepresentation != GuidRepresentation.Unspecified)
  163. {
  164. var expectedSubType = (_binaryWriterSettings.GuidRepresentation == GuidRepresentation.Standard) ? BsonBinarySubType.UuidStandard : BsonBinarySubType.UuidLegacy;
  165. if (subType != expectedSubType)
  166. {
  167. var message = string.Format(
  168. "The GuidRepresentation for the writer is {0}, which requires the subType argument to be {1}, not {2}.",
  169. _binaryWriterSettings.GuidRepresentation, expectedSubType, subType);
  170. throw new BsonSerializationException(message);
  171. }
  172. if (guidRepresentation != _binaryWriterSettings.GuidRepresentation)
  173. {
  174. var message = string.Format(
  175. "The GuidRepresentation for the writer is {0}, which requires the the guidRepresentation argument to also be {0}, not {1}.",
  176. _binaryWriterSettings.GuidRepresentation, guidRepresentation);
  177. throw new BsonSerializationException(message);
  178. }
  179. }
  180. break;
  181. }
  182. _buffer.WriteByte((byte)BsonType.Binary);
  183. WriteNameHelper();
  184. if (subType == BsonBinarySubType.OldBinary)
  185. {
  186. // sub type OldBinary has two sizes (for historical reasons)
  187. _buffer.WriteInt32(bytes.Length + 4);
  188. _buffer.WriteByte((byte)subType);
  189. _buffer.WriteInt32(bytes.Length);
  190. }
  191. else
  192. {
  193. _buffer.WriteInt32(bytes.Length);
  194. _buffer.WriteByte((byte)subType);
  195. }
  196. _buffer.WriteBytes(bytes);
  197. State = GetNextState();
  198. }
  199. #pragma warning restore 618
  200. /// <summary>
  201. /// Writes a BSON Boolean to the writer.
  202. /// </summary>
  203. /// <param name="value">The Boolean value.</param>
  204. public override void WriteBoolean(bool value)
  205. {
  206. if (Disposed) { throw new ObjectDisposedException("BsonBinaryWriter"); }
  207. if (State != BsonWriterState.Value)
  208. {
  209. ThrowInvalidState("WriteBoolean", BsonWriterState.Value);
  210. }
  211. _buffer.WriteByte((byte)BsonType.Boolean);
  212. WriteNameHelper();
  213. _buffer.WriteBoolean(value);
  214. State = GetNextState();
  215. }
  216. /// <summary>
  217. /// Writes BSON binary data to the writer.
  218. /// </summary>
  219. /// <param name="bytes">The bytes.</param>
  220. public override void WriteBytes(byte[] bytes)
  221. {
  222. if (Disposed) { throw new ObjectDisposedException("BsonBinaryWriter"); }
  223. if (State != BsonWriterState.Value)
  224. {
  225. ThrowInvalidState("WriteBytes", BsonWriterState.Value);
  226. }
  227. _buffer.WriteByte((byte)BsonType.Binary);
  228. WriteNameHelper();
  229. _buffer.WriteInt32(bytes.Length);
  230. _buffer.WriteByte((byte)BsonBinarySubType.Binary);
  231. _buffer.WriteBytes(bytes);
  232. State = GetNextState();
  233. }
  234. /// <summary>
  235. /// Writes a BSON DateTime to the writer.
  236. /// </summary>
  237. /// <param name="value">The number of milliseconds since the Unix epoch.</param>
  238. public override void WriteDateTime(long value)
  239. {
  240. if (Disposed) { throw new ObjectDisposedException("BsonBinaryWriter"); }
  241. if (State != BsonWriterState.Value)
  242. {
  243. ThrowInvalidState("WriteDateTime", BsonWriterState.Value);
  244. }
  245. _buffer.WriteByte((byte)BsonType.DateTime);
  246. WriteNameHelper();
  247. _buffer.WriteInt64(value);
  248. State = GetNextState();
  249. }
  250. /// <summary>
  251. /// Writes a BSON Double to the writer.
  252. /// </summary>
  253. /// <param name="value">The Double value.</param>
  254. public override void WriteDouble(double value)
  255. {
  256. if (Disposed) { throw new ObjectDisposedException("BsonBinaryWriter"); }
  257. if (State != BsonWriterState.Value)
  258. {
  259. ThrowInvalidState("WriteDouble", BsonWriterState.Value);
  260. }
  261. _buffer.WriteByte((byte)BsonType.Double);
  262. WriteNameHelper();
  263. _buffer.WriteDouble(value);
  264. State = GetNextState();
  265. }
  266. /// <summary>
  267. /// Writes the end of a BSON array to the writer.
  268. /// </summary>
  269. public override void WriteEndArray()
  270. {
  271. if (Disposed) { throw new ObjectDisposedException("BsonBinaryWriter"); }
  272. if (State != BsonWriterState.Value)
  273. {
  274. ThrowInvalidState("WriteEndArray", BsonWriterState.Value);
  275. }
  276. if (_context.ContextType != ContextType.Array)
  277. {
  278. ThrowInvalidContextType("WriteEndArray", _context.ContextType, ContextType.Array);
  279. }
  280. base.WriteEndArray();
  281. _buffer.WriteByte(0);
  282. BackpatchSize(); // size of document
  283. _context = _context.ParentContext;
  284. State = GetNextState();
  285. }
  286. /// <summary>
  287. /// Writes the end of a BSON document to the writer.
  288. /// </summary>
  289. public override void WriteEndDocument()
  290. {
  291. if (Disposed) { throw new ObjectDisposedException("BsonBinaryWriter"); }
  292. if (State != BsonWriterState.Name)
  293. {
  294. ThrowInvalidState("WriteEndDocument", BsonWriterState.Name);
  295. }
  296. if (_context.ContextType != ContextType.Document && _context.ContextType != ContextType.ScopeDocument)
  297. {
  298. ThrowInvalidContextType("WriteEndDocument", _context.ContextType, ContextType.Document, ContextType.ScopeDocument);
  299. }
  300. base.WriteEndDocument();
  301. _buffer.WriteByte(0);
  302. BackpatchSize(); // size of document
  303. _context = _context.ParentContext;
  304. if (_context == null)
  305. {
  306. State = BsonWriterState.Done;
  307. }
  308. else
  309. {
  310. if (_context.ContextType == ContextType.JavaScriptWithScope)
  311. {
  312. BackpatchSize(); // size of the JavaScript with scope value
  313. _context = _context.ParentContext;
  314. }
  315. State = GetNextState();
  316. }
  317. }
  318. /// <summary>
  319. /// Writes a BSON Int32 to the writer.
  320. /// </summary>
  321. /// <param name="value">The Int32 value.</param>
  322. public override void WriteInt32(int value)
  323. {
  324. if (Disposed) { throw new ObjectDisposedException("BsonBinaryWriter"); }
  325. if (State != BsonWriterState.Value)
  326. {
  327. ThrowInvalidState("WriteInt32", BsonWriterState.Value);
  328. }
  329. _buffer.WriteByte((byte)BsonType.Int32);
  330. WriteNameHelper();
  331. _buffer.WriteInt32(value);
  332. State = GetNextState();
  333. }
  334. /// <summary>
  335. /// Writes a BSON Int64 to the writer.
  336. /// </summary>
  337. /// <param name="value">The Int64 value.</param>
  338. public override void WriteInt64(long value)
  339. {
  340. if (Disposed) { throw new ObjectDisposedException("BsonBinaryWriter"); }
  341. if (State != BsonWriterState.Value)
  342. {
  343. ThrowInvalidState("WriteInt64", BsonWriterState.Value);
  344. }
  345. _buffer.WriteByte((byte)BsonType.Int64);
  346. WriteNameHelper();
  347. _buffer.WriteInt64(value);
  348. State = GetNextState();
  349. }
  350. /// <summary>
  351. /// Writes a BSON JavaScript to the writer.
  352. /// </summary>
  353. /// <param name="code">The JavaScript code.</param>
  354. public override void WriteJavaScript(string code)
  355. {
  356. if (Disposed) { throw new ObjectDisposedException("BsonBinaryWriter"); }
  357. if (State != BsonWriterState.Value)
  358. {
  359. ThrowInvalidState("WriteJavaScript", BsonWriterState.Value);
  360. }
  361. _buffer.WriteByte((byte)BsonType.JavaScript);
  362. WriteNameHelper();
  363. _buffer.WriteString(_binaryWriterSettings.Encoding, code);
  364. State = GetNextState();
  365. }
  366. /// <summary>
  367. /// Writes a BSON JavaScript to the writer (call WriteStartDocument to start writing the scope).
  368. /// </summary>
  369. /// <param name="code">The JavaScript code.</param>
  370. public override void WriteJavaScriptWithScope(string code)
  371. {
  372. if (Disposed) { throw new ObjectDisposedException("BsonBinaryWriter"); }
  373. if (State != BsonWriterState.Value)
  374. {
  375. ThrowInvalidState("WriteJavaScriptWithScope", BsonWriterState.Value);
  376. }
  377. _buffer.WriteByte((byte)BsonType.JavaScriptWithScope);
  378. WriteNameHelper();
  379. _context = new BsonBinaryWriterContext(_context, ContextType.JavaScriptWithScope, _buffer.Position);
  380. _buffer.WriteInt32(0); // reserve space for size of JavaScript with scope value
  381. _buffer.WriteString(_binaryWriterSettings.Encoding, code);
  382. State = BsonWriterState.ScopeDocument;
  383. }
  384. /// <summary>
  385. /// Writes a BSON MaxKey to the writer.
  386. /// </summary>
  387. public override void WriteMaxKey()
  388. {
  389. if (Disposed) { throw new ObjectDisposedException("BsonBinaryWriter"); }
  390. if (State != BsonWriterState.Value)
  391. {
  392. ThrowInvalidState("WriteMaxKey", BsonWriterState.Value);
  393. }
  394. _buffer.WriteByte((byte)BsonType.MaxKey);
  395. WriteNameHelper();
  396. State = GetNextState();
  397. }
  398. /// <summary>
  399. /// Writes a BSON MinKey to the writer.
  400. /// </summary>
  401. public override void WriteMinKey()
  402. {
  403. if (Disposed) { throw new ObjectDisposedException("BsonBinaryWriter"); }
  404. if (State != BsonWriterState.Value)
  405. {
  406. ThrowInvalidState("WriteMinKey", BsonWriterState.Value);
  407. }
  408. _buffer.WriteByte((byte)BsonType.MinKey);
  409. WriteNameHelper();
  410. State = GetNextState();
  411. }
  412. /// <summary>
  413. /// Writes a BSON null to the writer.
  414. /// </summary>
  415. public override void WriteNull()
  416. {
  417. if (Disposed) { throw new ObjectDisposedException("BsonBinaryWriter"); }
  418. if (State != BsonWriterState.Value)
  419. {
  420. ThrowInvalidState("WriteNull", BsonWriterState.Value);
  421. }
  422. _buffer.WriteByte((byte)BsonType.Null);
  423. WriteNameHelper();
  424. State = GetNextState();
  425. }
  426. /// <summary>
  427. /// Writes a BSON ObjectId to the writer.
  428. /// </summary>
  429. /// <param name="objectId">The ObjectId.</param>
  430. public override void WriteObjectId(ObjectId objectId)
  431. {
  432. if (Disposed) { throw new ObjectDisposedException("BsonBinaryWriter"); }
  433. if (State != BsonWriterState.Value)
  434. {
  435. ThrowInvalidState("WriteObjectId", BsonWriterState.Value);
  436. }
  437. _buffer.WriteByte((byte)BsonType.ObjectId);
  438. WriteNameHelper();
  439. _buffer.WriteObjectId(objectId);
  440. State = GetNextState();
  441. }
  442. /// <summary>
  443. /// Writes a raw BSON array.
  444. /// </summary>
  445. /// <param name="slice">The byte buffer containing the raw BSON array.</param>
  446. public override void WriteRawBsonArray(IByteBuffer slice)
  447. {
  448. if (Disposed) { throw new ObjectDisposedException("BsonBinaryWriter"); }
  449. if (State != BsonWriterState.Value)
  450. {
  451. ThrowInvalidState("WriteRawBsonArray", BsonWriterState.Value);
  452. }
  453. _buffer.WriteByte((byte)BsonType.Array);
  454. WriteNameHelper();
  455. _buffer.ByteBuffer.WriteBytes(slice); // assumes byteBuffer is a valid raw BSON array
  456. State = GetNextState();
  457. }
  458. /// <summary>
  459. /// Writes a raw BSON document.
  460. /// </summary>
  461. /// <param name="slice">The byte buffer containing the raw BSON document.</param>
  462. public override void WriteRawBsonDocument(IByteBuffer slice)
  463. {
  464. if (Disposed) { throw new ObjectDisposedException("BsonBinaryWriter"); }
  465. if (State != BsonWriterState.Initial && State != BsonWriterState.Value && State != BsonWriterState.ScopeDocument && State != BsonWriterState.Done)
  466. {
  467. ThrowInvalidState("WriteRawBsonDocument", BsonWriterState.Initial, BsonWriterState.Value, BsonWriterState.ScopeDocument, BsonWriterState.Done);
  468. }
  469. if (State == BsonWriterState.Value)
  470. {
  471. _buffer.WriteByte((byte)BsonType.Document);
  472. WriteNameHelper();
  473. }
  474. _buffer.ByteBuffer.WriteBytes(slice); // assumes byteBuffer is a valid raw BSON document
  475. if (_context == null)
  476. {
  477. State = BsonWriterState.Done;
  478. }
  479. else
  480. {
  481. if (_context.ContextType == ContextType.JavaScriptWithScope)
  482. {
  483. BackpatchSize(); // size of the JavaScript with scope value
  484. _context = _context.ParentContext;
  485. }
  486. State = GetNextState();
  487. }
  488. }
  489. /// <summary>
  490. /// Writes a BSON regular expression to the writer.
  491. /// </summary>
  492. /// <param name="regex">A BsonRegularExpression.</param>
  493. public override void WriteRegularExpression(BsonRegularExpression regex)
  494. {
  495. if (Disposed) { throw new ObjectDisposedException("BsonBinaryWriter"); }
  496. if (State != BsonWriterState.Value)
  497. {
  498. ThrowInvalidState("WriteRegularExpression", BsonWriterState.Value);
  499. }
  500. _buffer.WriteByte((byte)BsonType.RegularExpression);
  501. WriteNameHelper();
  502. _buffer.WriteCString(_binaryWriterSettings.Encoding, regex.Pattern);
  503. _buffer.WriteCString(_binaryWriterSettings.Encoding, regex.Options);
  504. State = GetNextState();
  505. }
  506. /// <summary>
  507. /// Writes the start of a BSON array to the writer.
  508. /// </summary>
  509. public override void WriteStartArray()
  510. {
  511. if (Disposed) { throw new ObjectDisposedException("BsonBinaryWriter"); }
  512. if (State != BsonWriterState.Value)
  513. {
  514. ThrowInvalidState("WriteStartArray", BsonWriterState.Value);
  515. }
  516. base.WriteStartArray();
  517. _buffer.WriteByte((byte)BsonType.Array);
  518. WriteNameHelper();
  519. _context = new BsonBinaryWriterContext(_context, ContextType.Array, _buffer.Position);
  520. _buffer.WriteInt32(0); // reserve space for size
  521. State = BsonWriterState.Value;
  522. }
  523. /// <summary>
  524. /// Writes the start of a BSON document to the writer.
  525. /// </summary>
  526. public override void WriteStartDocument()
  527. {
  528. if (Disposed) { throw new ObjectDisposedException("BsonBinaryWriter"); }
  529. if (State != BsonWriterState.Initial && State != BsonWriterState.Value && State != BsonWriterState.ScopeDocument && State != BsonWriterState.Done)
  530. {
  531. ThrowInvalidState("WriteStartDocument", BsonWriterState.Initial, BsonWriterState.Value, BsonWriterState.ScopeDocument, BsonWriterState.Done);
  532. }
  533. base.WriteStartDocument();
  534. if (State == BsonWriterState.Value)
  535. {
  536. _buffer.WriteByte((byte)BsonType.Document);
  537. WriteNameHelper();
  538. }
  539. _context = new BsonBinaryWriterContext(_context, ContextType.Document, _buffer.Position);
  540. _buffer.WriteInt32(0); // reserve space for size
  541. State = BsonWriterState.Name;
  542. }
  543. /// <summary>
  544. /// Writes a BSON String to the writer.
  545. /// </summary>
  546. /// <param name="value">The String value.</param>
  547. public override void WriteString(string value)
  548. {
  549. if (Disposed) { throw new ObjectDisposedException("BsonBinaryWriter"); }
  550. if (State != BsonWriterState.Value)
  551. {
  552. ThrowInvalidState("WriteString", BsonWriterState.Value);
  553. }
  554. _buffer.WriteByte((byte)BsonType.String);
  555. WriteNameHelper();
  556. _buffer.WriteString(_binaryWriterSettings.Encoding, value);
  557. State = GetNextState();
  558. }
  559. /// <summary>
  560. /// Writes a BSON Symbol to the writer.
  561. /// </summary>
  562. /// <param name="value">The symbol.</param>
  563. public override void WriteSymbol(string value)
  564. {
  565. if (Disposed) { throw new ObjectDisposedException("BsonBinaryWriter"); }
  566. if (State != BsonWriterState.Value)
  567. {
  568. ThrowInvalidState("WriteSymbol", BsonWriterState.Value);
  569. }
  570. _buffer.WriteByte((byte)BsonType.Symbol);
  571. WriteNameHelper();
  572. _buffer.WriteString(_binaryWriterSettings.Encoding, value);
  573. State = GetNextState();
  574. }
  575. /// <summary>
  576. /// Writes a BSON timestamp to the writer.
  577. /// </summary>
  578. /// <param name="value">The combined timestamp/increment value.</param>
  579. public override void WriteTimestamp(long value)
  580. {
  581. if (Disposed) { throw new ObjectDisposedException("BsonBinaryWriter"); }
  582. if (State != BsonWriterState.Value)
  583. {
  584. ThrowInvalidState("WriteTimestamp", BsonWriterState.Value);
  585. }
  586. _buffer.WriteByte((byte)BsonType.Timestamp);
  587. WriteNameHelper();
  588. _buffer.WriteInt64(value);
  589. State = GetNextState();
  590. }
  591. /// <summary>
  592. /// Writes a BSON undefined to the writer.
  593. /// </summary>
  594. public override void WriteUndefined()
  595. {
  596. if (Disposed) { throw new ObjectDisposedException("BsonBinaryWriter"); }
  597. if (State != BsonWriterState.Value)
  598. {
  599. ThrowInvalidState("WriteUndefined", BsonWriterState.Value);
  600. }
  601. _buffer.WriteByte((byte)BsonType.Undefined);
  602. WriteNameHelper();
  603. State = GetNextState();
  604. }
  605. // protected methods
  606. /// <summary>
  607. /// Disposes of any resources used by the writer.
  608. /// </summary>
  609. /// <param name="disposing">True if called from Dispose.</param>
  610. protected override void Dispose(bool disposing)
  611. {
  612. if (disposing)
  613. {
  614. Close();
  615. if (_buffer != null)
  616. {
  617. if (_disposeBuffer)
  618. {
  619. _buffer.Dispose();
  620. }
  621. _buffer = null;
  622. }
  623. }
  624. base.Dispose(disposing);
  625. }
  626. // private methods
  627. private void BackpatchSize()
  628. {
  629. int size = _buffer.Position - _context.StartPosition;
  630. if (size > _maxDocumentSizeStack.Peek())
  631. {
  632. var message = string.Format("Size {0} is larger than MaxDocumentSize {1}.", size, _maxDocumentSizeStack.Peek());
  633. throw new Exception(message);
  634. }
  635. _buffer.Backpatch(_context.StartPosition, size);
  636. }
  637. private BsonWriterState GetNextState()
  638. {
  639. if (_context.ContextType == ContextType.Array)
  640. {
  641. return BsonWriterState.Value;
  642. }
  643. else
  644. {
  645. return BsonWriterState.Name;
  646. }
  647. }
  648. private void WriteNameHelper()
  649. {
  650. string name;
  651. if (_context.ContextType == ContextType.Array)
  652. {
  653. name = (_context.Index++).ToString();
  654. }
  655. else
  656. {
  657. name = Name;
  658. }
  659. _buffer.WriteCString(__strictUtf8Encoding, name);
  660. }
  661. }
  662. }