BsonBinaryWriter.cs 27 KB

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