RawBsonArray.cs 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668
  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;
  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 array that is represented using only the raw bytes.
  28. /// </summary>
  29. [BsonSerializer(typeof(RawBsonArraySerializer))]
  30. public class RawBsonArray : BsonArray, 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="RawBsonArray"/> class.
  40. /// </summary>
  41. /// <param name="slice">The slice.</param>
  42. /// <exception cref="System.ArgumentNullException">slice</exception>
  43. /// <exception cref="System.ArgumentException">RawBsonArray cannot be used with an IByteBuffer that needs disposing.</exception>
  44. public RawBsonArray(IByteBuffer slice)
  45. {
  46. if (slice == null)
  47. {
  48. throw new ArgumentNullException("slice");
  49. }
  50. _slice = slice;
  51. }
  52. // public properties
  53. /// <summary>
  54. /// Gets or sets the total number of elements the internal data structure can hold without resizing.
  55. /// </summary>
  56. public override int Capacity
  57. {
  58. get
  59. {
  60. ThrowIfDisposed();
  61. return _slice.Capacity;
  62. }
  63. set
  64. {
  65. throw new NotSupportedException("RawBsonArray instances are immutable.");
  66. }
  67. }
  68. /// <summary>
  69. /// Gets the count of array elements.
  70. /// </summary>
  71. public override int Count
  72. {
  73. get
  74. {
  75. ThrowIfDisposed();
  76. using (var stream = new ByteBufferStream(_slice, ownsBuffer: false))
  77. using (var bsonReader = new BsonBinaryReader(stream, _readerSettings))
  78. {
  79. var count = 0;
  80. bsonReader.ReadStartDocument();
  81. while (bsonReader.ReadBsonType() != BsonType.EndOfDocument)
  82. {
  83. bsonReader.SkipName();
  84. bsonReader.SkipValue();
  85. count++;
  86. }
  87. bsonReader.ReadEndDocument();
  88. return count;
  89. }
  90. }
  91. }
  92. /// <summary>
  93. /// Gets whether the array is read-only.
  94. /// </summary>
  95. public override bool IsReadOnly
  96. {
  97. get { return true; }
  98. }
  99. /// <summary>
  100. /// Gets the array elements as raw values (see BsonValue.RawValue).
  101. /// </summary>
  102. [Obsolete("Use ToArray to ToList instead.")]
  103. public override IEnumerable<object> RawValues
  104. {
  105. get
  106. {
  107. ThrowIfDisposed();
  108. using (var stream = new ByteBufferStream(_slice, ownsBuffer: false))
  109. using (var bsonReader = new BsonBinaryReader(stream, _readerSettings))
  110. {
  111. var context = BsonDeserializationContext.CreateRoot(bsonReader);
  112. bsonReader.ReadStartDocument();
  113. while (bsonReader.ReadBsonType() != BsonType.EndOfDocument)
  114. {
  115. bsonReader.SkipName();
  116. yield return DeserializeBsonValue(context).RawValue;
  117. }
  118. bsonReader.ReadEndDocument();
  119. }
  120. }
  121. }
  122. /// <summary>
  123. /// Gets the slice.
  124. /// </summary>
  125. /// <value>
  126. /// The slice.
  127. /// </value>
  128. public IByteBuffer Slice
  129. {
  130. get { return _slice; }
  131. }
  132. /// <summary>
  133. /// Gets the array elements.
  134. /// </summary>
  135. public override IEnumerable<BsonValue> Values
  136. {
  137. get
  138. {
  139. ThrowIfDisposed();
  140. using (var stream = new ByteBufferStream(_slice, ownsBuffer: false))
  141. using (var bsonReader = new BsonBinaryReader(stream, _readerSettings))
  142. {
  143. var context = BsonDeserializationContext.CreateRoot(bsonReader);
  144. bsonReader.ReadStartDocument();
  145. while (bsonReader.ReadBsonType() != BsonType.EndOfDocument)
  146. {
  147. bsonReader.SkipName();
  148. yield return DeserializeBsonValue(context);
  149. }
  150. bsonReader.ReadEndDocument();
  151. }
  152. }
  153. }
  154. // public indexers
  155. /// <summary>
  156. /// Gets or sets a value by position.
  157. /// </summary>
  158. /// <param name="index">The position.</param>
  159. /// <returns>The value.</returns>
  160. public override BsonValue this[int index]
  161. {
  162. get
  163. {
  164. if (index < 0)
  165. {
  166. throw new ArgumentOutOfRangeException("index");
  167. }
  168. ThrowIfDisposed();
  169. using (var stream = new ByteBufferStream(_slice, ownsBuffer: false))
  170. using (var bsonReader = new BsonBinaryReader(stream, _readerSettings))
  171. {
  172. bsonReader.ReadStartDocument();
  173. var i = 0;
  174. while (bsonReader.ReadBsonType() != BsonType.EndOfDocument)
  175. {
  176. bsonReader.SkipName();
  177. if (i == index)
  178. {
  179. var context = BsonDeserializationContext.CreateRoot(bsonReader);
  180. return DeserializeBsonValue(context);
  181. }
  182. bsonReader.SkipValue();
  183. i++;
  184. }
  185. bsonReader.ReadEndDocument();
  186. throw new ArgumentOutOfRangeException("index");
  187. }
  188. }
  189. set
  190. {
  191. throw new NotSupportedException("RawBsonArray instances are immutable.");
  192. }
  193. }
  194. // public methods
  195. /// <summary>
  196. /// Adds an element to the array.
  197. /// </summary>
  198. /// <param name="value">The value to add to the array.</param>
  199. /// <returns>The array (so method calls can be chained).</returns>
  200. public override BsonArray Add(BsonValue value)
  201. {
  202. throw new NotSupportedException("RawBsonArray instances are immutable.");
  203. }
  204. /// <summary>
  205. /// Adds multiple elements to the array.
  206. /// </summary>
  207. /// <param name="values">A list of values to add to the array.</param>
  208. /// <returns>The array (so method calls can be chained).</returns>
  209. public override BsonArray AddRange(IEnumerable<bool> values)
  210. {
  211. throw new NotSupportedException("RawBsonArray instances are immutable.");
  212. }
  213. /// <summary>
  214. /// Adds multiple elements to the array.
  215. /// </summary>
  216. /// <param name="values">A list of values to add to the array.</param>
  217. /// <returns>The array (so method calls can be chained).</returns>
  218. public override BsonArray AddRange(IEnumerable<BsonValue> values)
  219. {
  220. throw new NotSupportedException("RawBsonArray instances are immutable.");
  221. }
  222. /// <summary>
  223. /// Adds multiple elements to the array.
  224. /// </summary>
  225. /// <param name="values">A list of values to add to the array.</param>
  226. /// <returns>The array (so method calls can be chained).</returns>
  227. public override BsonArray AddRange(IEnumerable<DateTime> values)
  228. {
  229. throw new NotSupportedException("RawBsonArray instances are immutable.");
  230. }
  231. /// <summary>
  232. /// Adds multiple elements to the array.
  233. /// </summary>
  234. /// <param name="values">A list of values to add to the array.</param>
  235. /// <returns>The array (so method calls can be chained).</returns>
  236. public override BsonArray AddRange(IEnumerable<double> values)
  237. {
  238. throw new NotSupportedException("RawBsonArray instances are immutable.");
  239. }
  240. /// <summary>
  241. /// Adds multiple elements to the array.
  242. /// </summary>
  243. /// <param name="values">A list of values to add to the array.</param>
  244. /// <returns>The array (so method calls can be chained).</returns>
  245. public override BsonArray AddRange(IEnumerable<int> values)
  246. {
  247. throw new NotSupportedException("RawBsonArray instances are immutable.");
  248. }
  249. /// <summary>
  250. /// Adds multiple elements to the array.
  251. /// </summary>
  252. /// <param name="values">A list of values to add to the array.</param>
  253. /// <returns>The array (so method calls can be chained).</returns>
  254. public override BsonArray AddRange(IEnumerable<long> values)
  255. {
  256. throw new NotSupportedException("RawBsonArray instances are immutable.");
  257. }
  258. /// <summary>
  259. /// Adds multiple elements to the array.
  260. /// </summary>
  261. /// <param name="values">A list of values to add to the array.</param>
  262. /// <returns>The array (so method calls can be chained).</returns>
  263. public override BsonArray AddRange(IEnumerable<ObjectId> values)
  264. {
  265. throw new NotSupportedException("RawBsonArray instances are immutable.");
  266. }
  267. /// <summary>
  268. /// Adds multiple elements to the array.
  269. /// </summary>
  270. /// <param name="values">A list of values to add to the array.</param>
  271. /// <returns>The array (so method calls can be chained).</returns>
  272. public override BsonArray AddRange(IEnumerable<string> values)
  273. {
  274. throw new NotSupportedException("RawBsonArray instances are immutable.");
  275. }
  276. /// <summary>
  277. /// Adds multiple elements to the array.
  278. /// </summary>
  279. /// <param name="values">A list of values to add to the array.</param>
  280. /// <returns>The array (so method calls can be chained).</returns>
  281. public override BsonArray AddRange(IEnumerable values)
  282. {
  283. throw new NotSupportedException("RawBsonArray instances are immutable.");
  284. }
  285. /// <summary>
  286. /// Creates a shallow clone of the array (see also DeepClone).
  287. /// </summary>
  288. /// <returns>A shallow clone of the array.</returns>
  289. public override BsonValue Clone()
  290. {
  291. return new RawBsonArray(CloneSlice());
  292. }
  293. /// <summary>
  294. /// Clears the array.
  295. /// </summary>
  296. public override void Clear()
  297. {
  298. throw new NotSupportedException("RawBsonArray instances are immutable.");
  299. }
  300. /// <summary>
  301. /// Tests whether the array contains a value.
  302. /// </summary>
  303. /// <param name="value">The value to test for.</param>
  304. /// <returns>True if the array contains the value.</returns>
  305. public override bool Contains(BsonValue value)
  306. {
  307. ThrowIfDisposed();
  308. using (var stream = new ByteBufferStream(_slice, ownsBuffer: false))
  309. using (var bsonReader = new BsonBinaryReader(stream, _readerSettings))
  310. {
  311. var context = BsonDeserializationContext.CreateRoot(bsonReader);
  312. bsonReader.ReadStartDocument();
  313. while (bsonReader.ReadBsonType() != BsonType.EndOfDocument)
  314. {
  315. bsonReader.SkipName();
  316. if (DeserializeBsonValue(context).Equals(value))
  317. {
  318. return true;
  319. }
  320. }
  321. bsonReader.ReadEndDocument();
  322. return false;
  323. }
  324. }
  325. /// <summary>
  326. /// Copies elements from this array to another array.
  327. /// </summary>
  328. /// <param name="array">The other array.</param>
  329. /// <param name="arrayIndex">The zero based index of the other array at which to start copying.</param>
  330. public override void CopyTo(BsonValue[] array, int arrayIndex)
  331. {
  332. ThrowIfDisposed();
  333. using (var stream = new ByteBufferStream(_slice, ownsBuffer: false))
  334. using (var bsonReader = new BsonBinaryReader(stream, _readerSettings))
  335. {
  336. var context = BsonDeserializationContext.CreateRoot(bsonReader);
  337. bsonReader.ReadStartDocument();
  338. while (bsonReader.ReadBsonType() != BsonType.EndOfDocument)
  339. {
  340. bsonReader.SkipName();
  341. array[arrayIndex++] = DeserializeBsonValue(context);
  342. }
  343. bsonReader.ReadEndDocument();
  344. }
  345. }
  346. /// <summary>
  347. /// Copies elements from this array to another array as raw values (see BsonValue.RawValue).
  348. /// </summary>
  349. /// <param name="array">The other array.</param>
  350. /// <param name="arrayIndex">The zero based index of the other array at which to start copying.</param>
  351. [Obsolete("Use ToArray or ToList instead.")]
  352. public override void CopyTo(object[] array, int arrayIndex)
  353. {
  354. ThrowIfDisposed();
  355. using (var stream = new ByteBufferStream(_slice, ownsBuffer: false))
  356. using (var bsonReader = new BsonBinaryReader(stream, _readerSettings))
  357. {
  358. var context = BsonDeserializationContext.CreateRoot(bsonReader);
  359. bsonReader.ReadStartDocument();
  360. while (bsonReader.ReadBsonType() != BsonType.EndOfDocument)
  361. {
  362. bsonReader.SkipName();
  363. array[arrayIndex++] = DeserializeBsonValue(context).RawValue;
  364. }
  365. bsonReader.ReadEndDocument();
  366. }
  367. }
  368. /// <summary>
  369. /// Creates a deep clone of the array (see also Clone).
  370. /// </summary>
  371. /// <returns>A deep clone of the array.</returns>
  372. public override BsonValue DeepClone()
  373. {
  374. ThrowIfDisposed();
  375. return new RawBsonArray(CloneSlice());
  376. }
  377. /// <summary>
  378. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  379. /// </summary>
  380. public void Dispose()
  381. {
  382. Dispose(true);
  383. GC.SuppressFinalize(this);
  384. }
  385. /// <summary>
  386. /// Gets an enumerator that can enumerate the elements of the array.
  387. /// </summary>
  388. /// <returns>An enumerator.</returns>
  389. public override IEnumerator<BsonValue> GetEnumerator()
  390. {
  391. ThrowIfDisposed();
  392. using (var stream = new ByteBufferStream(_slice, ownsBuffer: false))
  393. using (var bsonReader = new BsonBinaryReader(stream, _readerSettings))
  394. {
  395. var context = BsonDeserializationContext.CreateRoot(bsonReader);
  396. bsonReader.ReadStartDocument();
  397. while (bsonReader.ReadBsonType() != BsonType.EndOfDocument)
  398. {
  399. bsonReader.SkipName();
  400. yield return DeserializeBsonValue(context);
  401. }
  402. bsonReader.ReadEndDocument();
  403. }
  404. }
  405. /// <summary>
  406. /// Gets the index of a value in the array.
  407. /// </summary>
  408. /// <param name="value">The value to search for.</param>
  409. /// <returns>The zero based index of the value (or -1 if not found).</returns>
  410. public override int IndexOf(BsonValue value)
  411. {
  412. return IndexOf(value, 0, int.MaxValue);
  413. }
  414. /// <summary>
  415. /// Gets the index of a value in the array.
  416. /// </summary>
  417. /// <param name="value">The value to search for.</param>
  418. /// <param name="index">The zero based index at which to start the search.</param>
  419. /// <returns>The zero based index of the value (or -1 if not found).</returns>
  420. public override int IndexOf(BsonValue value, int index)
  421. {
  422. return IndexOf(value, index, int.MaxValue);
  423. }
  424. /// <summary>
  425. /// Gets the index of a value in the array.
  426. /// </summary>
  427. /// <param name="value">The value to search for.</param>
  428. /// <param name="index">The zero based index at which to start the search.</param>
  429. /// <param name="count">The number of elements to search.</param>
  430. /// <returns>The zero based index of the value (or -1 if not found).</returns>
  431. public override int IndexOf(BsonValue value, int index, int count)
  432. {
  433. ThrowIfDisposed();
  434. using (var stream = new ByteBufferStream(_slice, ownsBuffer: false))
  435. using (var bsonReader = new BsonBinaryReader(stream, _readerSettings))
  436. {
  437. var context = BsonDeserializationContext.CreateRoot(bsonReader);
  438. bsonReader.ReadStartDocument();
  439. var i = 0;
  440. while (bsonReader.ReadBsonType() != BsonType.EndOfDocument)
  441. {
  442. bsonReader.SkipName();
  443. if (i >= index)
  444. {
  445. if (count == 0)
  446. {
  447. return -1;
  448. }
  449. if (DeserializeBsonValue(context).Equals(value))
  450. {
  451. return i;
  452. }
  453. count--;
  454. }
  455. else
  456. {
  457. bsonReader.SkipValue();
  458. }
  459. i++;
  460. }
  461. bsonReader.ReadEndDocument();
  462. return -1;
  463. }
  464. }
  465. /// <summary>
  466. /// Inserts a new value into the array.
  467. /// </summary>
  468. /// <param name="index">The zero based index at which to insert the new value.</param>
  469. /// <param name="value">The new value.</param>
  470. public override void Insert(int index, BsonValue value)
  471. {
  472. throw new NotSupportedException("RawBsonArray instances are immutable.");
  473. }
  474. /// <summary>
  475. /// Materializes the RawBsonArray into a regular BsonArray.
  476. /// </summary>
  477. /// <param name="binaryReaderSettings">The binary reader settings.</param>
  478. /// <returns>A BsonArray.</returns>
  479. public BsonArray Materialize(BsonBinaryReaderSettings binaryReaderSettings)
  480. {
  481. ThrowIfDisposed();
  482. // because BsonBinaryReader can only read documents at the top level we have to wrap the RawBsonArray in a document
  483. var document = new BsonDocument("array", this);
  484. var bytes = document.ToBson();
  485. using (var stream = new MemoryStream(bytes))
  486. using (var reader = new BsonBinaryReader(stream, binaryReaderSettings))
  487. {
  488. var context = BsonDeserializationContext.CreateRoot(reader);
  489. var materializedDocument = BsonDocumentSerializer.Instance.Deserialize(context);
  490. return materializedDocument["array"].AsBsonArray;
  491. }
  492. }
  493. /// <summary>
  494. /// Removes the first occurrence of a value from the array.
  495. /// </summary>
  496. /// <param name="value">The value to remove.</param>
  497. /// <returns>True if the value was removed.</returns>
  498. public override bool Remove(BsonValue value)
  499. {
  500. throw new NotSupportedException("RawBsonArray instances are immutable.");
  501. }
  502. /// <summary>
  503. /// Removes an element from the array.
  504. /// </summary>
  505. /// <param name="index">The zero based index of the element to remove.</param>
  506. public override void RemoveAt(int index)
  507. {
  508. throw new NotSupportedException("RawBsonArray instances are immutable.");
  509. }
  510. /// <summary>
  511. /// Converts the BsonArray to an array of BsonValues.
  512. /// </summary>
  513. /// <returns>An array of BsonValues.</returns>
  514. public override BsonValue[] ToArray()
  515. {
  516. ThrowIfDisposed();
  517. return Values.ToArray();
  518. }
  519. /// <summary>
  520. /// Converts the BsonArray to a list of BsonValues.
  521. /// </summary>
  522. /// <returns>A list of BsonValues.</returns>
  523. public override List<BsonValue> ToList()
  524. {
  525. ThrowIfDisposed();
  526. return Values.ToList();
  527. }
  528. /// <summary>
  529. /// Returns a string representation of the array.
  530. /// </summary>
  531. /// <returns>A string representation of the array.</returns>
  532. public override string ToString()
  533. {
  534. ThrowIfDisposed();
  535. var parts = Values.Select(v => v.ToString()).ToArray();
  536. return string.Format("[{0}]", string.Join(", ", parts));
  537. }
  538. // protected methods
  539. /// <summary>
  540. /// Releases unmanaged and - optionally - managed resources.
  541. /// </summary>
  542. /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  543. protected virtual void Dispose(bool disposing)
  544. {
  545. if (!_disposed)
  546. {
  547. if (disposing)
  548. {
  549. if (_slice != null)
  550. {
  551. _slice.Dispose();
  552. _slice = null;
  553. }
  554. if (_disposableItems != null)
  555. {
  556. _disposableItems.ForEach(x => x.Dispose());
  557. _disposableItems = null;
  558. }
  559. }
  560. _disposed = true;
  561. }
  562. }
  563. /// <summary>
  564. /// Throws if disposed.
  565. /// </summary>
  566. /// <exception cref="System.ObjectDisposedException"></exception>
  567. protected void ThrowIfDisposed()
  568. {
  569. if (_disposed)
  570. {
  571. throw new ObjectDisposedException(GetType().Name);
  572. }
  573. }
  574. // private methods
  575. private IByteBuffer CloneSlice()
  576. {
  577. return _slice.GetSlice(0, _slice.Length);
  578. }
  579. private RawBsonArray DeserializeRawBsonArray(IBsonReader bsonReader)
  580. {
  581. var slice = bsonReader.ReadRawBsonArray();
  582. var nestedArray = new RawBsonArray(slice);
  583. _disposableItems.Add(nestedArray);
  584. return nestedArray;
  585. }
  586. private RawBsonDocument DeserializeRawBsonDocument(IBsonReader bsonReader)
  587. {
  588. var slice = bsonReader.ReadRawBsonDocument();
  589. var nestedDocument = new RawBsonDocument(slice);
  590. _disposableItems.Add(nestedDocument);
  591. return nestedDocument;
  592. }
  593. private BsonValue DeserializeBsonValue(BsonDeserializationContext context)
  594. {
  595. var bsonReader = context.Reader;
  596. switch (bsonReader.GetCurrentBsonType())
  597. {
  598. case BsonType.Array: return DeserializeRawBsonArray(bsonReader);
  599. case BsonType.Document: return DeserializeRawBsonDocument(bsonReader);
  600. default: return BsonValueSerializer.Instance.Deserialize(context);
  601. }
  602. }
  603. }
  604. }