RawBsonDocument.cs 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952
  1. /* Copyright 2010-2015 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;
  17. using System.Collections.Generic;
  18. using System.IO;
  19. using System.Linq;
  20. using MongoDB.Bson.IO;
  21. using MongoDB.Bson.Serialization;
  22. using MongoDB.Bson.Serialization.Attributes;
  23. using MongoDB.Bson.Serialization.Serializers;
  24. namespace MongoDB.Bson
  25. {
  26. /// <summary>
  27. /// Represents an immutable BSON document that is represented using only the raw bytes.
  28. /// </summary>
  29. [BsonSerializer(typeof(RawBsonDocumentSerializer))]
  30. public class RawBsonDocument : BsonDocument, IDisposable
  31. {
  32. // private fields
  33. private bool _disposed;
  34. private IByteBuffer _slice;
  35. private List<IDisposable> _disposableItems = new List<IDisposable>();
  36. private BsonBinaryReaderSettings _readerSettings = BsonBinaryReaderSettings.Defaults;
  37. // constructors
  38. /// <summary>
  39. /// Initializes a new instance of the <see cref="RawBsonDocument"/> class.
  40. /// </summary>
  41. /// <param name="slice">The slice.</param>
  42. /// <exception cref="System.ArgumentNullException">slice</exception>
  43. /// <exception cref="System.ArgumentException">RawBsonDocument cannot be used with an IByteBuffer that needs disposing.</exception>
  44. public RawBsonDocument(IByteBuffer slice)
  45. {
  46. if (slice == null)
  47. {
  48. throw new ArgumentNullException("slice");
  49. }
  50. _slice = slice;
  51. }
  52. /// <summary>
  53. /// Initializes a new instance of the <see cref="RawBsonDocument"/> class.
  54. /// </summary>
  55. /// <param name="bytes">The bytes.</param>
  56. public RawBsonDocument(byte[] bytes)
  57. : this(new ByteArrayBuffer(bytes, isReadOnly: true))
  58. {
  59. }
  60. // public properties
  61. /// <summary>
  62. /// Gets the number of elements.
  63. /// </summary>
  64. public override int ElementCount
  65. {
  66. get
  67. {
  68. ThrowIfDisposed();
  69. using (var stream = new ByteBufferStream(_slice, ownsBuffer: false))
  70. using (var bsonReader = new BsonBinaryReader(stream, _readerSettings))
  71. {
  72. var elementCount = 0;
  73. bsonReader.ReadStartDocument();
  74. while (bsonReader.ReadBsonType() != BsonType.EndOfDocument)
  75. {
  76. bsonReader.SkipName();
  77. bsonReader.SkipValue();
  78. elementCount++;
  79. }
  80. bsonReader.ReadEndDocument();
  81. return elementCount;
  82. }
  83. }
  84. }
  85. /// <summary>
  86. /// Gets the elements.
  87. /// </summary>
  88. public override IEnumerable<BsonElement> Elements
  89. {
  90. get
  91. {
  92. ThrowIfDisposed();
  93. using (var stream = new ByteBufferStream(_slice, ownsBuffer: false))
  94. using (var bsonReader = new BsonBinaryReader(stream, _readerSettings))
  95. {
  96. var context = BsonDeserializationContext.CreateRoot(bsonReader);
  97. bsonReader.ReadStartDocument();
  98. while (bsonReader.ReadBsonType() != BsonType.EndOfDocument)
  99. {
  100. var name = bsonReader.ReadName();
  101. var value = DeserializeBsonValue(context);
  102. yield return new BsonElement(name, value);
  103. }
  104. bsonReader.ReadEndDocument();
  105. }
  106. }
  107. }
  108. /// <summary>
  109. /// Gets the element names.
  110. /// </summary>
  111. public override IEnumerable<string> Names
  112. {
  113. get
  114. {
  115. ThrowIfDisposed();
  116. using (var stream = new ByteBufferStream(_slice, ownsBuffer: false))
  117. using (var bsonReader = new BsonBinaryReader(stream, _readerSettings))
  118. {
  119. bsonReader.ReadStartDocument();
  120. while (bsonReader.ReadBsonType() != BsonType.EndOfDocument)
  121. {
  122. yield return bsonReader.ReadName();
  123. bsonReader.SkipValue();
  124. }
  125. bsonReader.ReadEndDocument();
  126. }
  127. }
  128. }
  129. /// <summary>
  130. /// Gets the raw values (see BsonValue.RawValue).
  131. /// </summary>
  132. [Obsolete("Use Values instead.")]
  133. public override IEnumerable<object> RawValues
  134. {
  135. get
  136. {
  137. ThrowIfDisposed();
  138. using (var stream = new ByteBufferStream(_slice, ownsBuffer: false))
  139. using (var bsonReader = new BsonBinaryReader(stream, _readerSettings))
  140. {
  141. var context = BsonDeserializationContext.CreateRoot(bsonReader);
  142. bsonReader.ReadStartDocument();
  143. while (bsonReader.ReadBsonType() != BsonType.EndOfDocument)
  144. {
  145. bsonReader.SkipName();
  146. yield return DeserializeBsonValue(context).RawValue;
  147. }
  148. bsonReader.ReadEndDocument();
  149. }
  150. }
  151. }
  152. /// <summary>
  153. /// Gets the slice.
  154. /// </summary>
  155. /// <value>
  156. /// The slice.
  157. /// </value>
  158. public IByteBuffer Slice
  159. {
  160. get { return _slice; }
  161. }
  162. /// <summary>
  163. /// Gets the values.
  164. /// </summary>
  165. public override IEnumerable<BsonValue> Values
  166. {
  167. get
  168. {
  169. ThrowIfDisposed();
  170. using (var stream = new ByteBufferStream(_slice, ownsBuffer: false))
  171. using (var bsonReader = new BsonBinaryReader(stream, _readerSettings))
  172. {
  173. var context = BsonDeserializationContext.CreateRoot(bsonReader);
  174. bsonReader.ReadStartDocument();
  175. while (bsonReader.ReadBsonType() != BsonType.EndOfDocument)
  176. {
  177. bsonReader.SkipName();
  178. yield return DeserializeBsonValue(context);
  179. }
  180. bsonReader.ReadEndDocument();
  181. }
  182. }
  183. }
  184. // public indexers
  185. /// <summary>
  186. /// Gets or sets a value by position.
  187. /// </summary>
  188. /// <param name="index">The position.</param>
  189. /// <returns>The value.</returns>
  190. public override BsonValue this[int index]
  191. {
  192. get { return GetValue(index); }
  193. set { Set(index, value); }
  194. }
  195. /// <summary>
  196. /// Gets the value of an element or a default value if the element is not found.
  197. /// </summary>
  198. /// <param name="name">The name of the element.</param>
  199. /// <param name="defaultValue">The default value to return if the element is not found.</param>
  200. /// <returns>Teh value of the element or a default value if the element is not found.</returns>
  201. [Obsolete("Use GetValue(string name, BsonValue defaultValue) instead.")]
  202. public override BsonValue this[string name, BsonValue defaultValue]
  203. {
  204. get { return GetValue(name, defaultValue); }
  205. }
  206. /// <summary>
  207. /// Gets or sets a value by name.
  208. /// </summary>
  209. /// <param name="name">The name.</param>
  210. /// <returns>The value.</returns>
  211. public override BsonValue this[string name]
  212. {
  213. get { return GetValue(name); }
  214. set { Set(name, value); }
  215. }
  216. // public methods
  217. /// <summary>
  218. /// Adds an element to the document.
  219. /// </summary>
  220. /// <param name="element">The element to add.</param>
  221. /// <returns>
  222. /// The document (so method calls can be chained).
  223. /// </returns>
  224. public override BsonDocument Add(BsonElement element)
  225. {
  226. throw new NotSupportedException("RawBsonDocument instances are immutable.");
  227. }
  228. /// <summary>
  229. /// Adds elements to the document from a dictionary of key/value pairs.
  230. /// </summary>
  231. /// <param name="dictionary">The dictionary.</param>
  232. /// <returns>The document (so method calls can be chained).</returns>
  233. [Obsolete("Use AddRange instead.")]
  234. public override BsonDocument Add(Dictionary<string, object> dictionary)
  235. {
  236. throw new NotSupportedException("RawBsonDocument instances are immutable.");
  237. }
  238. /// <summary>
  239. /// Adds elements to the document from a dictionary of key/value pairs.
  240. /// </summary>
  241. /// <param name="dictionary">The dictionary.</param>
  242. /// <param name="keys">Which keys of the hash table to add.</param>
  243. /// <returns>The document (so method calls can be chained).</returns>
  244. [Obsolete("Use AddRange(IEnumerable<BsonElement> elements) instead.")]
  245. public override BsonDocument Add(Dictionary<string, object> dictionary, IEnumerable<string> keys)
  246. {
  247. throw new NotSupportedException("RawBsonDocument instances are immutable.");
  248. }
  249. /// <summary>
  250. /// Adds elements to the document from a dictionary of key/value pairs.
  251. /// </summary>
  252. /// <param name="dictionary">The dictionary.</param>
  253. /// <returns>The document (so method calls can be chained).</returns>
  254. [Obsolete("Use AddRange instead.")]
  255. public override BsonDocument Add(IDictionary<string, object> dictionary)
  256. {
  257. throw new NotSupportedException("RawBsonDocument instances are immutable.");
  258. }
  259. /// <summary>
  260. /// Adds elements to the document from a dictionary of key/value pairs.
  261. /// </summary>
  262. /// <param name="dictionary">The dictionary.</param>
  263. /// <param name="keys">Which keys of the hash table to add.</param>
  264. /// <returns>The document (so method calls can be chained).</returns>
  265. [Obsolete("Use AddRange(IEnumerable<BsonElement> elements) instead.")]
  266. public override BsonDocument Add(IDictionary<string, object> dictionary, IEnumerable<string> keys)
  267. {
  268. throw new NotSupportedException("RawBsonDocument instances are immutable.");
  269. }
  270. /// <summary>
  271. /// Adds elements to the document from a dictionary of key/value pairs.
  272. /// </summary>
  273. /// <param name="dictionary">The dictionary.</param>
  274. /// <returns>The document (so method calls can be chained).</returns>
  275. [Obsolete("Use AddRange instead.")]
  276. public override BsonDocument Add(IDictionary dictionary)
  277. {
  278. throw new NotSupportedException("RawBsonDocument instances are immutable.");
  279. }
  280. /// <summary>
  281. /// Adds elements to the document from a dictionary of key/value pairs.
  282. /// </summary>
  283. /// <param name="dictionary">The dictionary.</param>
  284. /// <param name="keys">Which keys of the hash table to add.</param>
  285. /// <returns>The document (so method calls can be chained).</returns>
  286. [Obsolete("Use AddRange(IEnumerable<BsonElement> elements) instead.")]
  287. public override BsonDocument Add(IDictionary dictionary, IEnumerable keys)
  288. {
  289. throw new NotSupportedException("RawBsonDocument instances are immutable.");
  290. }
  291. /// <summary>
  292. /// Adds a list of elements to the document.
  293. /// </summary>
  294. /// <param name="elements">The list of elements.</param>
  295. /// <returns>The document (so method calls can be chained).</returns>
  296. [Obsolete("Use AddRange instead.")]
  297. public override BsonDocument Add(IEnumerable<BsonElement> elements)
  298. {
  299. throw new NotSupportedException("RawBsonDocument instances are immutable.");
  300. }
  301. /// <summary>
  302. /// Adds a list of elements to the document.
  303. /// </summary>
  304. /// <param name="elements">The list of elements.</param>
  305. /// <returns>The document (so method calls can be chained).</returns>
  306. [Obsolete("Use AddRange(IEnumerable<BsonElement> elements) instead.")]
  307. public override BsonDocument Add(params BsonElement[] elements)
  308. {
  309. throw new NotSupportedException("RawBsonDocument instances are immutable.");
  310. }
  311. /// <summary>
  312. /// Creates and adds an element to the document.
  313. /// </summary>
  314. /// <param name="name">The name of the element.</param>
  315. /// <param name="value">The value of the element.</param>
  316. /// <returns>
  317. /// The document (so method calls can be chained).
  318. /// </returns>
  319. public override BsonDocument Add(string name, BsonValue value)
  320. {
  321. throw new NotSupportedException("RawBsonDocument instances are immutable.");
  322. }
  323. /// <summary>
  324. /// Creates and adds an element to the document, but only if the condition is true.
  325. /// </summary>
  326. /// <param name="name">The name of the element.</param>
  327. /// <param name="value">The value of the element.</param>
  328. /// <param name="condition">Whether to add the element to the document.</param>
  329. /// <returns>The document (so method calls can be chained).</returns>
  330. public override BsonDocument Add(string name, BsonValue value, bool condition)
  331. {
  332. throw new NotSupportedException("RawBsonDocument instances are immutable.");
  333. }
  334. /// <summary>
  335. /// Adds elements to the document from a dictionary of key/value pairs.
  336. /// </summary>
  337. /// <param name="dictionary">The dictionary.</param>
  338. /// <returns>
  339. /// The document (so method calls can be chained).
  340. /// </returns>
  341. public override BsonDocument AddRange(Dictionary<string, object> dictionary)
  342. {
  343. throw new NotSupportedException("RawBsonDocument instances are immutable.");
  344. }
  345. /// <summary>
  346. /// Adds elements to the document from a dictionary of key/value pairs.
  347. /// </summary>
  348. /// <param name="dictionary">The dictionary.</param>
  349. /// <returns>
  350. /// The document (so method calls can be chained).
  351. /// </returns>
  352. public override BsonDocument AddRange(IDictionary dictionary)
  353. {
  354. throw new NotSupportedException("RawBsonDocument instances are immutable.");
  355. }
  356. /// <summary>
  357. /// Adds a list of elements to the document.
  358. /// </summary>
  359. /// <param name="elements">The list of elements.</param>
  360. /// <returns>
  361. /// The document (so method calls can be chained).
  362. /// </returns>
  363. public override BsonDocument AddRange(IEnumerable<BsonElement> elements)
  364. {
  365. throw new NotSupportedException("RawBsonDocument instances are immutable.");
  366. }
  367. /// <summary>
  368. /// Adds elements to the document from a dictionary of key/value pairs.
  369. /// </summary>
  370. /// <param name="dictionary">The dictionary.</param>
  371. /// <returns>
  372. /// The document (so method calls can be chained).
  373. /// </returns>
  374. public override BsonDocument AddRange(IEnumerable<KeyValuePair<string, object>> dictionary)
  375. {
  376. throw new NotSupportedException("RawBsonDocument instances are immutable.");
  377. }
  378. /// <summary>
  379. /// Clears the document (removes all elements).
  380. /// </summary>
  381. public override void Clear()
  382. {
  383. throw new NotSupportedException("RawBsonDocument instances are immutable.");
  384. }
  385. /// <summary>
  386. /// Creates a shallow clone of the document (see also DeepClone).
  387. /// </summary>
  388. /// <returns>
  389. /// A shallow clone of the document.
  390. /// </returns>
  391. public override BsonValue Clone()
  392. {
  393. ThrowIfDisposed();
  394. return new RawBsonDocument(CloneSlice());
  395. }
  396. /// <summary>
  397. /// Tests whether the document contains an element with the specified name.
  398. /// </summary>
  399. /// <param name="name">The name of the element to look for.</param>
  400. /// <returns>
  401. /// True if the document contains an element with the specified name.
  402. /// </returns>
  403. public override bool Contains(string name)
  404. {
  405. if (name == null)
  406. {
  407. throw new ArgumentNullException("name");
  408. }
  409. ThrowIfDisposed();
  410. using (var stream = new ByteBufferStream(_slice, ownsBuffer: false))
  411. using (var bsonReader = new BsonBinaryReader(stream, _readerSettings))
  412. {
  413. bsonReader.ReadStartDocument();
  414. while (bsonReader.ReadBsonType() != BsonType.EndOfDocument)
  415. {
  416. if (bsonReader.ReadName() == name)
  417. {
  418. return true;
  419. }
  420. bsonReader.SkipValue();
  421. }
  422. bsonReader.ReadEndDocument();
  423. return false;
  424. }
  425. }
  426. /// <summary>
  427. /// Tests whether the document contains an element with the specified value.
  428. /// </summary>
  429. /// <param name="value">The value of the element to look for.</param>
  430. /// <returns>
  431. /// True if the document contains an element with the specified value.
  432. /// </returns>
  433. public override bool ContainsValue(BsonValue value)
  434. {
  435. ThrowIfDisposed();
  436. using (var stream = new ByteBufferStream(_slice, ownsBuffer: false))
  437. using (var bsonReader = new BsonBinaryReader(stream, _readerSettings))
  438. {
  439. var context = BsonDeserializationContext.CreateRoot(bsonReader);
  440. bsonReader.ReadStartDocument();
  441. while (bsonReader.ReadBsonType() != BsonType.EndOfDocument)
  442. {
  443. bsonReader.SkipName();
  444. if (DeserializeBsonValue(context).Equals(value))
  445. {
  446. return true;
  447. }
  448. }
  449. bsonReader.ReadEndDocument();
  450. return false;
  451. }
  452. }
  453. /// <summary>
  454. /// Creates a deep clone of the document (see also Clone).
  455. /// </summary>
  456. /// <returns>
  457. /// A deep clone of the document.
  458. /// </returns>
  459. public override BsonValue DeepClone()
  460. {
  461. ThrowIfDisposed();
  462. return new RawBsonDocument(CloneSlice());
  463. }
  464. /// <summary>
  465. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  466. /// </summary>
  467. public void Dispose()
  468. {
  469. Dispose(true);
  470. GC.SuppressFinalize(this);
  471. }
  472. /// <summary>
  473. /// Gets an element of this document.
  474. /// </summary>
  475. /// <param name="index">The zero based index of the element.</param>
  476. /// <returns>
  477. /// The element.
  478. /// </returns>
  479. public override BsonElement GetElement(int index)
  480. {
  481. if (index < 0)
  482. {
  483. throw new ArgumentOutOfRangeException("index");
  484. }
  485. ThrowIfDisposed();
  486. using (var stream = new ByteBufferStream(_slice, ownsBuffer: false))
  487. using (var bsonReader = new BsonBinaryReader(stream, _readerSettings))
  488. {
  489. var context = BsonDeserializationContext.CreateRoot(bsonReader);
  490. bsonReader.ReadStartDocument();
  491. var i = 0;
  492. while (bsonReader.ReadBsonType() != BsonType.EndOfDocument)
  493. {
  494. if (i == index)
  495. {
  496. var name = bsonReader.ReadName();
  497. var value = DeserializeBsonValue(context);
  498. return new BsonElement(name, value);
  499. }
  500. bsonReader.SkipName();
  501. bsonReader.SkipValue();
  502. i++;
  503. }
  504. bsonReader.ReadEndDocument();
  505. throw new ArgumentOutOfRangeException("index");
  506. }
  507. }
  508. /// <summary>
  509. /// Gets an element of this document.
  510. /// </summary>
  511. /// <param name="name">The name of the element.</param>
  512. /// <returns>
  513. /// A BsonElement.
  514. /// </returns>
  515. public override BsonElement GetElement(string name)
  516. {
  517. ThrowIfDisposed();
  518. BsonElement element;
  519. if (TryGetElement(name, out element))
  520. {
  521. return element;
  522. }
  523. string message = string.Format("Element '{0}' not found.", name);
  524. throw new KeyNotFoundException(message);
  525. }
  526. /// <summary>
  527. /// Gets an enumerator that can be used to enumerate the elements of this document.
  528. /// </summary>
  529. /// <returns>
  530. /// An enumerator.
  531. /// </returns>
  532. public override IEnumerator<BsonElement> GetEnumerator()
  533. {
  534. ThrowIfDisposed();
  535. using (var stream = new ByteBufferStream(_slice, ownsBuffer: false))
  536. using (var bsonReader = new BsonBinaryReader(stream, _readerSettings))
  537. {
  538. var context = BsonDeserializationContext.CreateRoot(bsonReader);
  539. bsonReader.ReadStartDocument();
  540. while (bsonReader.ReadBsonType() != BsonType.EndOfDocument)
  541. {
  542. var name = bsonReader.ReadName();
  543. var value = DeserializeBsonValue(context);
  544. yield return new BsonElement(name, value);
  545. }
  546. bsonReader.ReadEndDocument();
  547. }
  548. }
  549. /// <summary>
  550. /// Gets the value of an element.
  551. /// </summary>
  552. /// <param name="index">The zero based index of the element.</param>
  553. /// <returns>
  554. /// The value of the element.
  555. /// </returns>
  556. public override BsonValue GetValue(int index)
  557. {
  558. if (index < 0)
  559. {
  560. throw new ArgumentOutOfRangeException("index");
  561. }
  562. ThrowIfDisposed();
  563. using (var stream = new ByteBufferStream(_slice, ownsBuffer: false))
  564. using (var bsonReader = new BsonBinaryReader(stream, _readerSettings))
  565. {
  566. var context = BsonDeserializationContext.CreateRoot(bsonReader);
  567. bsonReader.ReadStartDocument();
  568. var i = 0;
  569. while (bsonReader.ReadBsonType() != BsonType.EndOfDocument)
  570. {
  571. bsonReader.SkipName();
  572. if (i == index)
  573. {
  574. return DeserializeBsonValue(context);
  575. }
  576. bsonReader.SkipValue();
  577. i++;
  578. }
  579. bsonReader.ReadEndDocument();
  580. throw new ArgumentOutOfRangeException("index");
  581. }
  582. }
  583. /// <summary>
  584. /// Gets the value of an element.
  585. /// </summary>
  586. /// <param name="name">The name of the element.</param>
  587. /// <returns>
  588. /// The value of the element.
  589. /// </returns>
  590. public override BsonValue GetValue(string name)
  591. {
  592. ThrowIfDisposed();
  593. BsonValue value;
  594. if (TryGetValue(name, out value))
  595. {
  596. return value;
  597. }
  598. string message = string.Format("Element '{0}' not found.", name);
  599. throw new KeyNotFoundException(message);
  600. }
  601. /// <summary>
  602. /// Gets the value of an element or a default value if the element is not found.
  603. /// </summary>
  604. /// <param name="name">The name of the element.</param>
  605. /// <param name="defaultValue">The default value returned if the element is not found.</param>
  606. /// <returns>
  607. /// The value of the element or the default value if the element is not found.
  608. /// </returns>
  609. public override BsonValue GetValue(string name, BsonValue defaultValue)
  610. {
  611. ThrowIfDisposed();
  612. BsonValue value;
  613. if (TryGetValue(name, out value))
  614. {
  615. return value;
  616. }
  617. return defaultValue;
  618. }
  619. /// <summary>
  620. /// Inserts a new element at a specified position.
  621. /// </summary>
  622. /// <param name="index">The position of the new element.</param>
  623. /// <param name="element">The element.</param>
  624. public override void InsertAt(int index, BsonElement element)
  625. {
  626. throw new NotSupportedException("RawBsonDocument instances are immutable.");
  627. }
  628. /// <summary>
  629. /// Materializes the RawBsonDocument into a regular BsonDocument.
  630. /// </summary>
  631. /// <param name="binaryReaderSettings">The binary reader settings.</param>
  632. /// <returns>A BsonDocument.</returns>
  633. public BsonDocument Materialize(BsonBinaryReaderSettings binaryReaderSettings)
  634. {
  635. ThrowIfDisposed();
  636. using (var stream = new ByteBufferStream(_slice, ownsBuffer: false))
  637. using (var reader = new BsonBinaryReader(stream, binaryReaderSettings))
  638. {
  639. var context = BsonDeserializationContext.CreateRoot(reader);
  640. return BsonDocumentSerializer.Instance.Deserialize(context);
  641. }
  642. }
  643. /// <summary>
  644. /// Merges another document into this one. Existing elements are not overwritten.
  645. /// </summary>
  646. /// <param name="document">The other document.</param>
  647. /// <returns>
  648. /// The document (so method calls can be chained).
  649. /// </returns>
  650. public override BsonDocument Merge(BsonDocument document)
  651. {
  652. throw new NotSupportedException("RawBsonDocument instances are immutable.");
  653. }
  654. /// <summary>
  655. /// Merges another document into this one, specifying whether existing elements are overwritten.
  656. /// </summary>
  657. /// <param name="document">The other document.</param>
  658. /// <param name="overwriteExistingElements">Whether to overwrite existing elements.</param>
  659. /// <returns>
  660. /// The document (so method calls can be chained).
  661. /// </returns>
  662. public override BsonDocument Merge(BsonDocument document, bool overwriteExistingElements)
  663. {
  664. throw new NotSupportedException("RawBsonDocument instances are immutable.");
  665. }
  666. /// <summary>
  667. /// Removes an element from this document (if duplicate element names are allowed
  668. /// then all elements with this name will be removed).
  669. /// </summary>
  670. /// <param name="name">The name of the element to remove.</param>
  671. public override void Remove(string name)
  672. {
  673. throw new NotSupportedException("RawBsonDocument instances are immutable.");
  674. }
  675. /// <summary>
  676. /// Removes an element from this document.
  677. /// </summary>
  678. /// <param name="index">The zero based index of the element to remove.</param>
  679. public override void RemoveAt(int index)
  680. {
  681. throw new NotSupportedException("RawBsonDocument instances are immutable.");
  682. }
  683. /// <summary>
  684. /// Removes an element from this document.
  685. /// </summary>
  686. /// <param name="element">The element to remove.</param>
  687. public override void RemoveElement(BsonElement element)
  688. {
  689. throw new NotSupportedException("RawBsonDocument instances are immutable.");
  690. }
  691. /// <summary>
  692. /// Sets the value of an element.
  693. /// </summary>
  694. /// <param name="index">The zero based index of the element whose value is to be set.</param>
  695. /// <param name="value">The new value.</param>
  696. /// <returns>
  697. /// The document (so method calls can be chained).
  698. /// </returns>
  699. public override BsonDocument Set(int index, BsonValue value)
  700. {
  701. throw new NotSupportedException("RawBsonDocument instances are immutable.");
  702. }
  703. /// <summary>
  704. /// Sets the value of an element (an element will be added if no element with this name is found).
  705. /// </summary>
  706. /// <param name="name">The name of the element whose value is to be set.</param>
  707. /// <param name="value">The new value.</param>
  708. /// <returns>
  709. /// The document (so method calls can be chained).
  710. /// </returns>
  711. public override BsonDocument Set(string name, BsonValue value)
  712. {
  713. throw new NotSupportedException("RawBsonDocument instances are immutable.");
  714. }
  715. /// <summary>
  716. /// Sets an element of the document (replaces any existing element with the same name or adds a new element if an element with the same name is not found).
  717. /// </summary>
  718. /// <param name="element">The new element.</param>
  719. /// <returns>
  720. /// The document.
  721. /// </returns>
  722. public override BsonDocument SetElement(BsonElement element)
  723. {
  724. throw new NotSupportedException("RawBsonDocument instances are immutable.");
  725. }
  726. /// <summary>
  727. /// Sets an element of the document (replacing the existing element at that position).
  728. /// </summary>
  729. /// <param name="index">The zero based index of the element to replace.</param>
  730. /// <param name="element">The new element.</param>
  731. /// <returns>
  732. /// The document.
  733. /// </returns>
  734. public override BsonDocument SetElement(int index, BsonElement element)
  735. {
  736. throw new NotSupportedException("RawBsonDocument instances are immutable.");
  737. }
  738. /// <summary>
  739. /// Tries to get an element of this document.
  740. /// </summary>
  741. /// <param name="name">The name of the element.</param>
  742. /// <param name="element">The element.</param>
  743. /// <returns>
  744. /// True if an element with that name was found.
  745. /// </returns>
  746. public override bool TryGetElement(string name, out BsonElement element)
  747. {
  748. ThrowIfDisposed();
  749. using (var stream = new ByteBufferStream(_slice, ownsBuffer: false))
  750. using (var bsonReader = new BsonBinaryReader(stream, _readerSettings))
  751. {
  752. var context = BsonDeserializationContext.CreateRoot(bsonReader);
  753. bsonReader.ReadStartDocument();
  754. while (bsonReader.ReadBsonType() != BsonType.EndOfDocument)
  755. {
  756. if (bsonReader.ReadName() == name)
  757. {
  758. var value = DeserializeBsonValue(context);
  759. element = new BsonElement(name, value);
  760. return true;
  761. }
  762. bsonReader.SkipValue();
  763. }
  764. bsonReader.ReadEndDocument();
  765. element = default(BsonElement);
  766. return false;
  767. }
  768. }
  769. /// <summary>
  770. /// Tries to get the value of an element of this document.
  771. /// </summary>
  772. /// <param name="name">The name of the element.</param>
  773. /// <param name="value">The value of the element.</param>
  774. /// <returns>
  775. /// True if an element with that name was found.
  776. /// </returns>
  777. public override bool TryGetValue(string name, out BsonValue value)
  778. {
  779. ThrowIfDisposed();
  780. using (var stream = new ByteBufferStream(_slice, ownsBuffer: false))
  781. using (var bsonReader = new BsonBinaryReader(stream, _readerSettings))
  782. {
  783. var context = BsonDeserializationContext.CreateRoot(bsonReader);
  784. bsonReader.ReadStartDocument();
  785. while (bsonReader.ReadBsonType() != BsonType.EndOfDocument)
  786. {
  787. if (bsonReader.ReadName() == name)
  788. {
  789. value = DeserializeBsonValue(context);
  790. return true;
  791. }
  792. bsonReader.SkipValue();
  793. }
  794. bsonReader.ReadEndDocument();
  795. value = null;
  796. return false;
  797. }
  798. }
  799. // protected methods
  800. /// <summary>
  801. /// Releases unmanaged and - optionally - managed resources.
  802. /// </summary>
  803. /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  804. protected virtual void Dispose(bool disposing)
  805. {
  806. if (!_disposed)
  807. {
  808. if (disposing)
  809. {
  810. if (_slice != null)
  811. {
  812. _slice.Dispose();
  813. _slice = null;
  814. }
  815. if (_disposableItems != null)
  816. {
  817. _disposableItems.ForEach(x => x.Dispose());
  818. _disposableItems = null;
  819. }
  820. }
  821. _disposed = true;
  822. }
  823. }
  824. /// <summary>
  825. /// Throws if disposed.
  826. /// </summary>
  827. /// <exception cref="System.ObjectDisposedException">RawBsonDocument</exception>
  828. protected void ThrowIfDisposed()
  829. {
  830. if (_disposed)
  831. {
  832. throw new ObjectDisposedException("RawBsonDocument");
  833. }
  834. }
  835. // private methods
  836. private IByteBuffer CloneSlice()
  837. {
  838. return _slice.GetSlice(0, _slice.Length);
  839. }
  840. private RawBsonArray DeserializeRawBsonArray(IBsonReader bsonReader)
  841. {
  842. var slice = bsonReader.ReadRawBsonArray();
  843. var nestedArray = new RawBsonArray(slice);
  844. _disposableItems.Add(nestedArray);
  845. return nestedArray;
  846. }
  847. private RawBsonDocument DeserializeRawBsonDocument(IBsonReader bsonReader)
  848. {
  849. var slice = bsonReader.ReadRawBsonDocument();
  850. var nestedDocument = new RawBsonDocument(slice);
  851. _disposableItems.Add(nestedDocument);
  852. return nestedDocument;
  853. }
  854. private BsonValue DeserializeBsonValue(BsonDeserializationContext context)
  855. {
  856. var bsonReader = context.Reader;
  857. switch (bsonReader.GetCurrentBsonType())
  858. {
  859. case BsonType.Array: return DeserializeRawBsonArray(bsonReader);
  860. case BsonType.Document: return DeserializeRawBsonDocument(bsonReader);
  861. default: return BsonValueSerializer.Instance.Deserialize(context);
  862. }
  863. }
  864. }
  865. }