BsonBinaryWriter.cs 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778
  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. switch (subType)
  157. {
  158. case BsonBinarySubType.OldBinary:
  159. if (Settings.FixOldBinarySubTypeOnOutput)
  160. {
  161. subType = BsonBinarySubType.Binary; // replace obsolete OldBinary with new Binary sub type
  162. }
  163. break;
  164. case BsonBinarySubType.UuidLegacy:
  165. case BsonBinarySubType.UuidStandard:
  166. if (BsonDefaults.GuidRepresentationMode == GuidRepresentationMode.V2)
  167. {
  168. if (Settings.GuidRepresentation != GuidRepresentation.Unspecified)
  169. {
  170. var expectedSubType = GuidConverter.GetSubType(Settings.GuidRepresentation);
  171. if (subType != expectedSubType)
  172. {
  173. var message = string.Format(
  174. "The GuidRepresentation for the writer is {0}, which requires the subType argument to be {1}, not {2}.",
  175. Settings.GuidRepresentation, expectedSubType, subType);
  176. throw new BsonSerializationException(message);
  177. }
  178. var guidRepresentation = binaryData.GuidRepresentation;
  179. if (guidRepresentation != Settings.GuidRepresentation)
  180. {
  181. var message = string.Format(
  182. "The GuidRepresentation for the writer is {0}, which requires the the guidRepresentation argument to also be {0}, not {1}.",
  183. Settings.GuidRepresentation, guidRepresentation);
  184. throw new BsonSerializationException(message);
  185. }
  186. }
  187. }
  188. break;
  189. }
  190. _bsonStream.WriteBsonType(BsonType.Binary);
  191. WriteNameHelper();
  192. if (subType == BsonBinarySubType.OldBinary)
  193. {
  194. // sub type OldBinary has two sizes (for historical reasons)
  195. _bsonStream.WriteInt32(bytes.Length + 4);
  196. _bsonStream.WriteBinarySubType(subType);
  197. _bsonStream.WriteInt32(bytes.Length);
  198. }
  199. else
  200. {
  201. _bsonStream.WriteInt32(bytes.Length);
  202. _bsonStream.WriteBinarySubType(subType);
  203. }
  204. _bsonStream.WriteBytes(bytes, 0, bytes.Length);
  205. State = GetNextState();
  206. }
  207. #pragma warning restore 618
  208. /// <summary>
  209. /// Writes a BSON Boolean to the writer.
  210. /// </summary>
  211. /// <param name="value">The Boolean value.</param>
  212. public override void WriteBoolean(bool value)
  213. {
  214. if (Disposed) { throw new ObjectDisposedException("BsonBinaryWriter"); }
  215. if (State != BsonWriterState.Value)
  216. {
  217. ThrowInvalidState("WriteBoolean", BsonWriterState.Value);
  218. }
  219. _bsonStream.WriteBsonType(BsonType.Boolean);
  220. WriteNameHelper();
  221. _bsonStream.WriteBoolean(value);
  222. State = GetNextState();
  223. }
  224. /// <summary>
  225. /// Writes BSON binary data to the writer.
  226. /// </summary>
  227. /// <param name="bytes">The bytes.</param>
  228. public override void WriteBytes(byte[] bytes)
  229. {
  230. if (Disposed) { throw new ObjectDisposedException("BsonBinaryWriter"); }
  231. if (State != BsonWriterState.Value)
  232. {
  233. ThrowInvalidState("WriteBytes", BsonWriterState.Value);
  234. }
  235. _bsonStream.WriteBsonType(BsonType.Binary);
  236. WriteNameHelper();
  237. _bsonStream.WriteInt32(bytes.Length);
  238. _bsonStream.WriteBinarySubType(BsonBinarySubType.Binary);
  239. _bsonStream.WriteBytes(bytes, 0, bytes.Length);
  240. State = GetNextState();
  241. }
  242. /// <summary>
  243. /// Writes a BSON DateTime to the writer.
  244. /// </summary>
  245. /// <param name="value">The number of milliseconds since the Unix epoch.</param>
  246. public override void WriteDateTime(long value)
  247. {
  248. if (Disposed) { throw new ObjectDisposedException("BsonBinaryWriter"); }
  249. if (State != BsonWriterState.Value)
  250. {
  251. ThrowInvalidState("WriteDateTime", BsonWriterState.Value);
  252. }
  253. _bsonStream.WriteBsonType(BsonType.DateTime);
  254. WriteNameHelper();
  255. _bsonStream.WriteInt64(value);
  256. State = GetNextState();
  257. }
  258. /// <inheritdoc />
  259. public override void WriteDecimal128(Decimal128 value)
  260. {
  261. if (Disposed) { throw new ObjectDisposedException("BsonBinaryWriter"); }
  262. if (State != BsonWriterState.Value)
  263. {
  264. ThrowInvalidState(nameof(WriteDecimal128), BsonWriterState.Value);
  265. }
  266. _bsonStream.WriteBsonType(BsonType.Decimal128);
  267. WriteNameHelper();
  268. _bsonStream.WriteDecimal128(value);
  269. State = GetNextState();
  270. }
  271. /// <summary>
  272. /// Writes a BSON Double to the writer.
  273. /// </summary>
  274. /// <param name="value">The Double value.</param>
  275. public override void WriteDouble(double value)
  276. {
  277. if (Disposed) { throw new ObjectDisposedException("BsonBinaryWriter"); }
  278. if (State != BsonWriterState.Value)
  279. {
  280. ThrowInvalidState("WriteDouble", BsonWriterState.Value);
  281. }
  282. _bsonStream.WriteBsonType(BsonType.Double);
  283. WriteNameHelper();
  284. _bsonStream.WriteDouble(value);
  285. State = GetNextState();
  286. }
  287. /// <summary>
  288. /// Writes the end of a BSON array to the writer.
  289. /// </summary>
  290. public override void WriteEndArray()
  291. {
  292. if (Disposed) { throw new ObjectDisposedException("BsonBinaryWriter"); }
  293. if (State != BsonWriterState.Value)
  294. {
  295. ThrowInvalidState("WriteEndArray", BsonWriterState.Value);
  296. }
  297. if (_context.ContextType != ContextType.Array)
  298. {
  299. ThrowInvalidContextType("WriteEndArray", _context.ContextType, ContextType.Array);
  300. }
  301. base.WriteEndArray();
  302. _bsonStream.WriteByte(0);
  303. BackpatchSize(); // size of document
  304. _context = _context.ParentContext;
  305. State = GetNextState();
  306. }
  307. /// <summary>
  308. /// Writes the end of a BSON document to the writer.
  309. /// </summary>
  310. public override void WriteEndDocument()
  311. {
  312. if (Disposed) { throw new ObjectDisposedException("BsonBinaryWriter"); }
  313. if (State != BsonWriterState.Name)
  314. {
  315. ThrowInvalidState("WriteEndDocument", BsonWriterState.Name);
  316. }
  317. if (_context.ContextType != ContextType.Document && _context.ContextType != ContextType.ScopeDocument)
  318. {
  319. ThrowInvalidContextType("WriteEndDocument", _context.ContextType, ContextType.Document, ContextType.ScopeDocument);
  320. }
  321. base.WriteEndDocument();
  322. _bsonStream.WriteByte(0);
  323. BackpatchSize(); // size of document
  324. _context = _context.ParentContext;
  325. if (_context == null)
  326. {
  327. State = BsonWriterState.Done;
  328. }
  329. else
  330. {
  331. if (_context.ContextType == ContextType.JavaScriptWithScope)
  332. {
  333. BackpatchSize(); // size of the JavaScript with scope value
  334. _context = _context.ParentContext;
  335. }
  336. State = GetNextState();
  337. }
  338. }
  339. /// <summary>
  340. /// Writes a BSON Int32 to the writer.
  341. /// </summary>
  342. /// <param name="value">The Int32 value.</param>
  343. public override void WriteInt32(int value)
  344. {
  345. if (Disposed) { throw new ObjectDisposedException("BsonBinaryWriter"); }
  346. if (State != BsonWriterState.Value)
  347. {
  348. ThrowInvalidState("WriteInt32", BsonWriterState.Value);
  349. }
  350. _bsonStream.WriteBsonType(BsonType.Int32);
  351. WriteNameHelper();
  352. _bsonStream.WriteInt32(value);
  353. State = GetNextState();
  354. }
  355. /// <summary>
  356. /// Writes a BSON Int64 to the writer.
  357. /// </summary>
  358. /// <param name="value">The Int64 value.</param>
  359. public override void WriteInt64(long value)
  360. {
  361. if (Disposed) { throw new ObjectDisposedException("BsonBinaryWriter"); }
  362. if (State != BsonWriterState.Value)
  363. {
  364. ThrowInvalidState("WriteInt64", BsonWriterState.Value);
  365. }
  366. _bsonStream.WriteBsonType(BsonType.Int64);
  367. WriteNameHelper();
  368. _bsonStream.WriteInt64(value);
  369. State = GetNextState();
  370. }
  371. /// <summary>
  372. /// Writes a BSON JavaScript to the writer.
  373. /// </summary>
  374. /// <param name="code">The JavaScript code.</param>
  375. public override void WriteJavaScript(string code)
  376. {
  377. if (Disposed) { throw new ObjectDisposedException("BsonBinaryWriter"); }
  378. if (State != BsonWriterState.Value)
  379. {
  380. ThrowInvalidState("WriteJavaScript", BsonWriterState.Value);
  381. }
  382. _bsonStream.WriteBsonType(BsonType.JavaScript);
  383. WriteNameHelper();
  384. _bsonStream.WriteString(code, Settings.Encoding);
  385. State = GetNextState();
  386. }
  387. /// <summary>
  388. /// Writes a BSON JavaScript to the writer (call WriteStartDocument to start writing the scope).
  389. /// </summary>
  390. /// <param name="code">The JavaScript code.</param>
  391. public override void WriteJavaScriptWithScope(string code)
  392. {
  393. if (Disposed) { throw new ObjectDisposedException("BsonBinaryWriter"); }
  394. if (State != BsonWriterState.Value)
  395. {
  396. ThrowInvalidState("WriteJavaScriptWithScope", BsonWriterState.Value);
  397. }
  398. _bsonStream.WriteBsonType(BsonType.JavaScriptWithScope);
  399. WriteNameHelper();
  400. _context = new BsonBinaryWriterContext(_context, ContextType.JavaScriptWithScope, _bsonStream.Position);
  401. _bsonStream.WriteInt32(0); // reserve space for size of JavaScript with scope value
  402. _bsonStream.WriteString(code, Settings.Encoding);
  403. State = BsonWriterState.ScopeDocument;
  404. }
  405. /// <summary>
  406. /// Writes a BSON MaxKey to the writer.
  407. /// </summary>
  408. public override void WriteMaxKey()
  409. {
  410. if (Disposed) { throw new ObjectDisposedException("BsonBinaryWriter"); }
  411. if (State != BsonWriterState.Value)
  412. {
  413. ThrowInvalidState("WriteMaxKey", BsonWriterState.Value);
  414. }
  415. _bsonStream.WriteBsonType(BsonType.MaxKey);
  416. WriteNameHelper();
  417. State = GetNextState();
  418. }
  419. /// <summary>
  420. /// Writes a BSON MinKey to the writer.
  421. /// </summary>
  422. public override void WriteMinKey()
  423. {
  424. if (Disposed) { throw new ObjectDisposedException("BsonBinaryWriter"); }
  425. if (State != BsonWriterState.Value)
  426. {
  427. ThrowInvalidState("WriteMinKey", BsonWriterState.Value);
  428. }
  429. _bsonStream.WriteBsonType(BsonType.MinKey);
  430. WriteNameHelper();
  431. State = GetNextState();
  432. }
  433. /// <summary>
  434. /// Writes a BSON null to the writer.
  435. /// </summary>
  436. public override void WriteNull()
  437. {
  438. if (Disposed) { throw new ObjectDisposedException("BsonBinaryWriter"); }
  439. if (State != BsonWriterState.Value)
  440. {
  441. ThrowInvalidState("WriteNull", BsonWriterState.Value);
  442. }
  443. _bsonStream.WriteBsonType(BsonType.Null);
  444. WriteNameHelper();
  445. State = GetNextState();
  446. }
  447. /// <summary>
  448. /// Writes a BSON ObjectId to the writer.
  449. /// </summary>
  450. /// <param name="objectId">The ObjectId.</param>
  451. public override void WriteObjectId(ObjectId objectId)
  452. {
  453. if (Disposed) { throw new ObjectDisposedException("BsonBinaryWriter"); }
  454. if (State != BsonWriterState.Value)
  455. {
  456. ThrowInvalidState("WriteObjectId", BsonWriterState.Value);
  457. }
  458. _bsonStream.WriteBsonType(BsonType.ObjectId);
  459. WriteNameHelper();
  460. _bsonStream.WriteObjectId(objectId);
  461. State = GetNextState();
  462. }
  463. /// <summary>
  464. /// Writes a raw BSON array.
  465. /// </summary>
  466. /// <param name="slice">The byte buffer containing the raw BSON array.</param>
  467. public override void WriteRawBsonArray(IByteBuffer slice)
  468. {
  469. if (Disposed) { throw new ObjectDisposedException("BsonBinaryWriter"); }
  470. if (State != BsonWriterState.Value)
  471. {
  472. ThrowInvalidState("WriteRawBsonArray", BsonWriterState.Value);
  473. }
  474. _bsonStream.WriteBsonType(BsonType.Array);
  475. WriteNameHelper();
  476. _bsonStream.WriteSlice(slice); // assumes slice is a valid raw BSON array
  477. State = GetNextState();
  478. }
  479. /// <summary>
  480. /// Writes a raw BSON document.
  481. /// </summary>
  482. /// <param name="slice">The byte buffer containing the raw BSON document.</param>
  483. public override void WriteRawBsonDocument(IByteBuffer slice)
  484. {
  485. if (Disposed) { throw new ObjectDisposedException("BsonBinaryWriter"); }
  486. if (State != BsonWriterState.Initial && State != BsonWriterState.Value && State != BsonWriterState.ScopeDocument && State != BsonWriterState.Done)
  487. {
  488. ThrowInvalidState("WriteRawBsonDocument", BsonWriterState.Initial, BsonWriterState.Value, BsonWriterState.ScopeDocument, BsonWriterState.Done);
  489. }
  490. if (State == BsonWriterState.Value)
  491. {
  492. _bsonStream.WriteBsonType(BsonType.Document);
  493. WriteNameHelper();
  494. }
  495. _bsonStream.WriteSlice(slice); // assumes byteBuffer is a valid raw BSON document
  496. if (_context == null)
  497. {
  498. State = BsonWriterState.Done;
  499. }
  500. else
  501. {
  502. if (_context.ContextType == ContextType.JavaScriptWithScope)
  503. {
  504. BackpatchSize(); // size of the JavaScript with scope value
  505. _context = _context.ParentContext;
  506. }
  507. State = GetNextState();
  508. }
  509. }
  510. /// <summary>
  511. /// Writes a BSON regular expression to the writer.
  512. /// </summary>
  513. /// <param name="regex">A BsonRegularExpression.</param>
  514. public override void WriteRegularExpression(BsonRegularExpression regex)
  515. {
  516. if (Disposed) { throw new ObjectDisposedException("BsonBinaryWriter"); }
  517. if (State != BsonWriterState.Value)
  518. {
  519. ThrowInvalidState("WriteRegularExpression", BsonWriterState.Value);
  520. }
  521. _bsonStream.WriteBsonType(BsonType.RegularExpression);
  522. WriteNameHelper();
  523. _bsonStream.WriteCString(regex.Pattern);
  524. _bsonStream.WriteCString(regex.Options);
  525. State = GetNextState();
  526. }
  527. /// <summary>
  528. /// Writes the start of a BSON array to the writer.
  529. /// </summary>
  530. public override void WriteStartArray()
  531. {
  532. if (Disposed) { throw new ObjectDisposedException("BsonBinaryWriter"); }
  533. if (State != BsonWriterState.Value)
  534. {
  535. ThrowInvalidState("WriteStartArray", BsonWriterState.Value);
  536. }
  537. base.WriteStartArray();
  538. _bsonStream.WriteBsonType(BsonType.Array);
  539. WriteNameHelper();
  540. _context = new BsonBinaryWriterContext(_context, ContextType.Array, _bsonStream.Position);
  541. _bsonStream.WriteInt32(0); // reserve space for size
  542. State = BsonWriterState.Value;
  543. }
  544. /// <summary>
  545. /// Writes the start of a BSON document to the writer.
  546. /// </summary>
  547. public override void WriteStartDocument()
  548. {
  549. if (Disposed) { throw new ObjectDisposedException("BsonBinaryWriter"); }
  550. if (State != BsonWriterState.Initial && State != BsonWriterState.Value && State != BsonWriterState.ScopeDocument && State != BsonWriterState.Done)
  551. {
  552. ThrowInvalidState("WriteStartDocument", BsonWriterState.Initial, BsonWriterState.Value, BsonWriterState.ScopeDocument, BsonWriterState.Done);
  553. }
  554. base.WriteStartDocument();
  555. if (State == BsonWriterState.Value)
  556. {
  557. _bsonStream.WriteBsonType(BsonType.Document);
  558. WriteNameHelper();
  559. }
  560. var contextType = (State == BsonWriterState.ScopeDocument) ? ContextType.ScopeDocument : ContextType.Document;
  561. _context = new BsonBinaryWriterContext(_context, contextType, _bsonStream.Position);
  562. _bsonStream.WriteInt32(0); // reserve space for size
  563. State = BsonWriterState.Name;
  564. }
  565. /// <summary>
  566. /// Writes a BSON String to the writer.
  567. /// </summary>
  568. /// <param name="value">The String value.</param>
  569. public override void WriteString(string value)
  570. {
  571. if (Disposed) { throw new ObjectDisposedException("BsonBinaryWriter"); }
  572. if (State != BsonWriterState.Value)
  573. {
  574. ThrowInvalidState("WriteString", BsonWriterState.Value);
  575. }
  576. _bsonStream.WriteBsonType(BsonType.String);
  577. WriteNameHelper();
  578. _bsonStream.WriteString(value, Settings.Encoding);
  579. State = GetNextState();
  580. }
  581. /// <summary>
  582. /// Writes a BSON Symbol to the writer.
  583. /// </summary>
  584. /// <param name="value">The symbol.</param>
  585. public override void WriteSymbol(string value)
  586. {
  587. if (Disposed) { throw new ObjectDisposedException("BsonBinaryWriter"); }
  588. if (State != BsonWriterState.Value)
  589. {
  590. ThrowInvalidState("WriteSymbol", BsonWriterState.Value);
  591. }
  592. _bsonStream.WriteBsonType(BsonType.Symbol);
  593. WriteNameHelper();
  594. _bsonStream.WriteString(value, Settings.Encoding);
  595. State = GetNextState();
  596. }
  597. /// <summary>
  598. /// Writes a BSON timestamp to the writer.
  599. /// </summary>
  600. /// <param name="value">The combined timestamp/increment value.</param>
  601. public override void WriteTimestamp(long value)
  602. {
  603. if (Disposed) { throw new ObjectDisposedException("BsonBinaryWriter"); }
  604. if (State != BsonWriterState.Value)
  605. {
  606. ThrowInvalidState("WriteTimestamp", BsonWriterState.Value);
  607. }
  608. _bsonStream.WriteBsonType(BsonType.Timestamp);
  609. WriteNameHelper();
  610. _bsonStream.WriteInt64(value);
  611. State = GetNextState();
  612. }
  613. /// <summary>
  614. /// Writes a BSON undefined to the writer.
  615. /// </summary>
  616. public override void WriteUndefined()
  617. {
  618. if (Disposed) { throw new ObjectDisposedException("BsonBinaryWriter"); }
  619. if (State != BsonWriterState.Value)
  620. {
  621. ThrowInvalidState("WriteUndefined", BsonWriterState.Value);
  622. }
  623. _bsonStream.WriteBsonType(BsonType.Undefined);
  624. WriteNameHelper();
  625. State = GetNextState();
  626. }
  627. // protected methods
  628. /// <summary>
  629. /// Disposes of any resources used by the writer.
  630. /// </summary>
  631. /// <param name="disposing">True if called from Dispose.</param>
  632. protected override void Dispose(bool disposing)
  633. {
  634. if (disposing)
  635. {
  636. try
  637. {
  638. Close();
  639. }
  640. catch { } // ignore exceptions
  641. }
  642. base.Dispose(disposing);
  643. }
  644. // private methods
  645. private void BackpatchSize()
  646. {
  647. var size = _bsonStream.Position - _context.StartPosition;
  648. if (size > Settings.MaxDocumentSize)
  649. {
  650. var message = string.Format("Size {0} is larger than MaxDocumentSize {1}.", size, Settings.MaxDocumentSize);
  651. throw new FormatException(message);
  652. }
  653. var currentPosition = _bsonStream.Position;
  654. _bsonStream.Position = _context.StartPosition;
  655. _bsonStream.WriteInt32((int)size);
  656. _bsonStream.Position = currentPosition;
  657. }
  658. private BsonWriterState GetNextState()
  659. {
  660. if (_context.ContextType == ContextType.Array)
  661. {
  662. return BsonWriterState.Value;
  663. }
  664. else
  665. {
  666. return BsonWriterState.Name;
  667. }
  668. }
  669. private void WriteNameHelper()
  670. {
  671. if (_context.ContextType == ContextType.Array)
  672. {
  673. var index = _context.Index++;
  674. var nameBytes = ArrayElementNameAccelerator.Default.GetElementNameBytes(index);
  675. _bsonStream.WriteCStringBytes(nameBytes);
  676. }
  677. else
  678. {
  679. _bsonStream.WriteCString(Name);
  680. }
  681. }
  682. }
  683. }