CodedOutputStream.cs 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960
  1. #region Copyright notice and license
  2. // Protocol Buffers - Google's data interchange format
  3. // Copyright 2008 Google Inc. All rights reserved.
  4. // http://github.com/jskeet/dotnet-protobufs/
  5. // Original C++/Java/Python code:
  6. // http://code.google.com/p/protobuf/
  7. //
  8. // Redistribution and use in source and binary forms, with or without
  9. // modification, are permitted provided that the following conditions are
  10. // met:
  11. //
  12. // * Redistributions of source code must retain the above copyright
  13. // notice, this list of conditions and the following disclaimer.
  14. // * Redistributions in binary form must reproduce the above
  15. // copyright notice, this list of conditions and the following disclaimer
  16. // in the documentation and/or other materials provided with the
  17. // distribution.
  18. // * Neither the name of Google Inc. nor the names of its
  19. // contributors may be used to endorse or promote products derived from
  20. // this software without specific prior written permission.
  21. //
  22. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  23. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  24. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  25. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  26. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  27. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  28. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  29. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  30. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  31. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  32. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  33. #endregion
  34. using System;
  35. using System.Collections;
  36. using System.IO;
  37. using System.Linq;
  38. using System.Text;
  39. using Google.Protobuf.Collections;
  40. using Google.Protobuf.Descriptors;
  41. namespace Google.Protobuf
  42. {
  43. /// <summary>
  44. /// Encodes and writes protocol message fields.
  45. /// </summary>
  46. /// <remarks>
  47. /// This class contains two kinds of methods: methods that write specific
  48. /// protocol message constructs and field types (e.g. WriteTag and
  49. /// WriteInt32) and methods that write low-level values (e.g.
  50. /// WriteRawVarint32 and WriteRawBytes). If you are writing encoded protocol
  51. /// messages, you should use the former methods, but if you are writing some
  52. /// other format of your own design, use the latter. The names of the former
  53. /// methods are taken from the protocol buffer type names, not .NET types.
  54. /// (Hence WriteFloat instead of WriteSingle, and WriteBool instead of WriteBoolean.)
  55. /// </remarks>
  56. public sealed partial class CodedOutputStream
  57. {
  58. // "Local" copy of Encoding.UTF8, for efficiency. (Yes, it makes a difference.)
  59. internal static readonly Encoding Utf8Encoding = Encoding.UTF8;
  60. /// <summary>
  61. /// The buffer size used by CreateInstance(Stream).
  62. /// </summary>
  63. public static readonly int DefaultBufferSize = 4096;
  64. private readonly byte[] buffer;
  65. private readonly int limit;
  66. private int position;
  67. private readonly Stream output;
  68. #region Construction
  69. private CodedOutputStream(byte[] buffer, int offset, int length)
  70. {
  71. this.output = null;
  72. this.buffer = buffer;
  73. this.position = offset;
  74. this.limit = offset + length;
  75. }
  76. private CodedOutputStream(Stream output, byte[] buffer)
  77. {
  78. this.output = output;
  79. this.buffer = buffer;
  80. this.position = 0;
  81. this.limit = buffer.Length;
  82. }
  83. /// <summary>
  84. /// Creates a new CodedOutputStream which write to the given stream.
  85. /// </summary>
  86. public static CodedOutputStream CreateInstance(Stream output)
  87. {
  88. return CreateInstance(output, DefaultBufferSize);
  89. }
  90. /// <summary>
  91. /// Creates a new CodedOutputStream which write to the given stream and uses
  92. /// the specified buffer size.
  93. /// </summary>
  94. public static CodedOutputStream CreateInstance(Stream output, int bufferSize)
  95. {
  96. return new CodedOutputStream(output, new byte[bufferSize]);
  97. }
  98. /// <summary>
  99. /// Creates a new CodedOutputStream that writes directly to the given
  100. /// byte array. If more bytes are written than fit in the array,
  101. /// OutOfSpaceException will be thrown.
  102. /// </summary>
  103. public static CodedOutputStream CreateInstance(byte[] flatArray)
  104. {
  105. return CreateInstance(flatArray, 0, flatArray.Length);
  106. }
  107. /// <summary>
  108. /// Creates a new CodedOutputStream that writes directly to the given
  109. /// byte array slice. If more bytes are written than fit in the array,
  110. /// OutOfSpaceException will be thrown.
  111. /// </summary>
  112. public static CodedOutputStream CreateInstance(byte[] flatArray, int offset, int length)
  113. {
  114. return new CodedOutputStream(flatArray, offset, length);
  115. }
  116. #endregion
  117. /// <summary>
  118. /// Returns the current position in the stream, or the position in the output buffer
  119. /// </summary>
  120. public long Position
  121. {
  122. get
  123. {
  124. if (output != null)
  125. {
  126. return output.Position + position;
  127. }
  128. return position;
  129. }
  130. }
  131. #region Writing of values without tags
  132. /// <summary>
  133. /// Writes a double field value, including tag, to the stream.
  134. /// </summary>
  135. public void WriteDouble(double value)
  136. {
  137. WriteRawLittleEndian64((ulong)FrameworkPortability.DoubleToInt64(value));
  138. }
  139. /// <summary>
  140. /// Writes a float field value, without a tag, to the stream.
  141. /// </summary>
  142. public void WriteFloat(float value)
  143. {
  144. byte[] rawBytes = BitConverter.GetBytes(value);
  145. if (!BitConverter.IsLittleEndian)
  146. {
  147. ByteArray.Reverse(rawBytes);
  148. }
  149. if (limit - position >= 4)
  150. {
  151. buffer[position++] = rawBytes[0];
  152. buffer[position++] = rawBytes[1];
  153. buffer[position++] = rawBytes[2];
  154. buffer[position++] = rawBytes[3];
  155. }
  156. else
  157. {
  158. WriteRawBytes(rawBytes, 0, 4);
  159. }
  160. }
  161. /// <summary>
  162. /// Writes a uint64 field value, without a tag, to the stream.
  163. /// </summary>
  164. public void WriteUInt64(ulong value)
  165. {
  166. WriteRawVarint64(value);
  167. }
  168. /// <summary>
  169. /// Writes an int64 field value, without a tag, to the stream.
  170. /// </summary>
  171. public void WriteInt64(long value)
  172. {
  173. WriteRawVarint64((ulong) value);
  174. }
  175. /// <summary>
  176. /// Writes an int32 field value, without a tag, to the stream.
  177. /// </summary>
  178. public void WriteInt32(int value)
  179. {
  180. if (value >= 0)
  181. {
  182. WriteRawVarint32((uint) value);
  183. }
  184. else
  185. {
  186. // Must sign-extend.
  187. WriteRawVarint64((ulong) value);
  188. }
  189. }
  190. /// <summary>
  191. /// Writes a fixed64 field value, without a tag, to the stream.
  192. /// </summary>
  193. public void WriteFixed64(ulong value)
  194. {
  195. WriteRawLittleEndian64(value);
  196. }
  197. /// <summary>
  198. /// Writes a fixed32 field value, without a tag, to the stream.
  199. /// </summary>
  200. public void WriteFixed32(uint value)
  201. {
  202. WriteRawLittleEndian32(value);
  203. }
  204. /// <summary>
  205. /// Writes a bool field value, without a tag, to the stream.
  206. /// </summary>
  207. public void WriteBool(bool value)
  208. {
  209. WriteRawByte(value ? (byte) 1 : (byte) 0);
  210. }
  211. /// <summary>
  212. /// Writes a string field value, without a tag, to the stream.
  213. /// </summary>
  214. public void WriteString(string value)
  215. {
  216. // Optimise the case where we have enough space to write
  217. // the string directly to the buffer, which should be common.
  218. int length = Utf8Encoding.GetByteCount(value);
  219. WriteRawVarint32((uint)length);
  220. if (limit - position >= length)
  221. {
  222. if (length == value.Length) // Must be all ASCII...
  223. {
  224. for (int i = 0; i < length; i++)
  225. {
  226. buffer[position + i] = (byte)value[i];
  227. }
  228. }
  229. else
  230. {
  231. Utf8Encoding.GetBytes(value, 0, value.Length, buffer, position);
  232. }
  233. position += length;
  234. }
  235. else
  236. {
  237. byte[] bytes = Utf8Encoding.GetBytes(value);
  238. WriteRawBytes(bytes);
  239. }
  240. }
  241. public void WriteMessage(IMessage value)
  242. {
  243. WriteRawVarint32((uint) value.CalculateSize());
  244. value.WriteTo(this);
  245. }
  246. public void WriteBytes(ByteString value)
  247. {
  248. WriteRawVarint32((uint) value.Length);
  249. value.WriteRawBytesTo(this);
  250. }
  251. public void WriteUInt32(uint value)
  252. {
  253. WriteRawVarint32(value);
  254. }
  255. public void WriteEnum(int value)
  256. {
  257. WriteInt32(value);
  258. }
  259. public void WriteSFixed32(int value)
  260. {
  261. WriteRawLittleEndian32((uint) value);
  262. }
  263. public void WriteSFixed64(long value)
  264. {
  265. WriteRawLittleEndian64((ulong) value);
  266. }
  267. public void WriteSInt32(int value)
  268. {
  269. WriteRawVarint32(EncodeZigZag32(value));
  270. }
  271. public void WriteSInt64(long value)
  272. {
  273. WriteRawVarint64(EncodeZigZag64(value));
  274. }
  275. #endregion
  276. #region Write array members, with fields.
  277. public void WriteMessageArray<T>(int fieldNumber, RepeatedField<T> list)
  278. where T : IMessage
  279. {
  280. foreach (T value in list)
  281. {
  282. WriteTag(fieldNumber, WireFormat.WireType.LengthDelimited);
  283. WriteMessage(value);
  284. }
  285. }
  286. public void WriteStringArray(int fieldNumber, RepeatedField<string> list)
  287. {
  288. foreach (var value in list)
  289. {
  290. WriteTag(fieldNumber, WireFormat.WireType.LengthDelimited);
  291. WriteString(value);
  292. }
  293. }
  294. public void WriteBytesArray(int fieldNumber, RepeatedField<ByteString> list)
  295. {
  296. foreach (var value in list)
  297. {
  298. WriteTag(fieldNumber, WireFormat.WireType.LengthDelimited);
  299. WriteBytes(value);
  300. }
  301. }
  302. public void WriteBoolArray(int fieldNumber, RepeatedField<bool> list)
  303. {
  304. foreach (var value in list)
  305. {
  306. WriteTag(fieldNumber, WireFormat.WireType.Varint);
  307. WriteBool(value);
  308. }
  309. }
  310. public void WriteInt32Array(int fieldNumber, RepeatedField<int> list)
  311. {
  312. foreach (var value in list)
  313. {
  314. WriteTag(fieldNumber, WireFormat.WireType.Varint);
  315. WriteInt32(value);
  316. }
  317. }
  318. public void WriteSInt32Array(int fieldNumber, RepeatedField<int> list)
  319. {
  320. foreach (var value in list)
  321. {
  322. WriteTag(fieldNumber, WireFormat.WireType.Varint);
  323. WriteSInt32(value);
  324. }
  325. }
  326. public void WriteUInt32Array(int fieldNumber, RepeatedField<uint> list)
  327. {
  328. foreach (var value in list)
  329. {
  330. WriteTag(fieldNumber, WireFormat.WireType.Varint);
  331. WriteUInt32(value);
  332. }
  333. }
  334. public void WriteFixed32Array(int fieldNumber, RepeatedField<uint> list)
  335. {
  336. foreach (var value in list)
  337. {
  338. WriteTag(fieldNumber, WireFormat.WireType.Fixed32);
  339. WriteFixed32(value);
  340. }
  341. }
  342. public void WriteSFixed32Array(int fieldNumber, RepeatedField<int> list)
  343. {
  344. foreach (var value in list)
  345. {
  346. WriteTag(fieldNumber, WireFormat.WireType.Fixed32);
  347. WriteSFixed32(value);
  348. }
  349. }
  350. public void WriteInt64Array(int fieldNumber, RepeatedField<long> list)
  351. {
  352. foreach (var value in list)
  353. {
  354. WriteTag(fieldNumber, WireFormat.WireType.Fixed64);
  355. WriteInt64(value);
  356. }
  357. }
  358. public void WriteSInt64Array(int fieldNumber, RepeatedField<long> list)
  359. {
  360. foreach (var value in list)
  361. {
  362. WriteTag(fieldNumber, WireFormat.WireType.Varint);
  363. WriteSInt64(value);
  364. }
  365. }
  366. public void WriteUInt64Array(int fieldNumber, RepeatedField<ulong> list)
  367. {
  368. foreach (var value in list)
  369. {
  370. WriteTag(fieldNumber, WireFormat.WireType.Varint);
  371. WriteUInt64(value);
  372. }
  373. }
  374. public void WriteFixed64Array(int fieldNumber, RepeatedField<ulong> list)
  375. {
  376. foreach (var value in list)
  377. {
  378. WriteTag(fieldNumber, WireFormat.WireType.Fixed64);
  379. WriteFixed64(value);
  380. }
  381. }
  382. public void WriteSFixed64Array(int fieldNumber, RepeatedField<long> list)
  383. {
  384. foreach (var value in list)
  385. {
  386. WriteTag(fieldNumber, WireFormat.WireType.Fixed64);
  387. WriteSFixed64(value);
  388. }
  389. }
  390. public void WriteDoubleArray(int fieldNumber, RepeatedField<double> list)
  391. {
  392. foreach (var value in list)
  393. {
  394. WriteTag(fieldNumber, WireFormat.WireType.Fixed64);
  395. WriteDouble(value);
  396. }
  397. }
  398. public void WriteFloatArray(int fieldNumber, RepeatedField<float> list)
  399. {
  400. foreach (var value in list)
  401. {
  402. WriteTag(fieldNumber, WireFormat.WireType.Fixed32);
  403. WriteFloat(value);
  404. }
  405. }
  406. public void WriteEnumArray<T>(int fieldNumber, RepeatedField<T> list)
  407. where T : struct, IComparable, IFormattable
  408. {
  409. // Bit of a hack, to access the values as ints
  410. var iterator = list.GetInt32Enumerator();
  411. while (iterator.MoveNext())
  412. {
  413. WriteTag(fieldNumber, WireFormat.WireType.Varint);
  414. WriteEnum(iterator.Current);
  415. }
  416. }
  417. #endregion
  418. #region Raw tag writing
  419. /// <summary>
  420. /// Encodes and writes a tag.
  421. /// </summary>
  422. public void WriteTag(int fieldNumber, WireFormat.WireType type)
  423. {
  424. WriteRawVarint32(WireFormat.MakeTag(fieldNumber, type));
  425. }
  426. /// <summary>
  427. /// Writes the given single-byte tag directly to the stream.
  428. /// </summary>
  429. public void WriteRawTag(byte b1)
  430. {
  431. WriteRawByte(b1);
  432. }
  433. /// <summary>
  434. /// Writes the given two-byte tag directly to the stream.
  435. /// </summary>
  436. public void WriteRawTag(byte b1, byte b2)
  437. {
  438. WriteRawByte(b1);
  439. WriteRawByte(b2);
  440. }
  441. /// <summary>
  442. /// Writes the given three-byte tag directly to the stream.
  443. /// </summary>
  444. public void WriteRawTag(byte b1, byte b2, byte b3)
  445. {
  446. WriteRawByte(b1);
  447. WriteRawByte(b2);
  448. WriteRawByte(b3);
  449. }
  450. /// <summary>
  451. /// Writes the given four-byte tag directly to the stream.
  452. /// </summary>
  453. public void WriteRawTag(byte b1, byte b2, byte b3, byte b4)
  454. {
  455. WriteRawByte(b1);
  456. WriteRawByte(b2);
  457. WriteRawByte(b3);
  458. WriteRawByte(b4);
  459. }
  460. /// <summary>
  461. /// Writes the given five-byte tag directly to the stream.
  462. /// </summary>
  463. public void WriteRawTag(byte b1, byte b2, byte b3, byte b4, byte b5)
  464. {
  465. WriteRawByte(b1);
  466. WriteRawByte(b2);
  467. WriteRawByte(b3);
  468. WriteRawByte(b4);
  469. WriteRawByte(b5);
  470. }
  471. #endregion
  472. #region Write packed array members
  473. // TODO(jonskeet): A lot of these are really inefficient, due to method group conversions. Fix!
  474. // (Alternatively, add extension methods to RepeatedField, accepting the Write* methods via delegates too.)
  475. public void WritePackedBoolArray(RepeatedField<bool> list)
  476. {
  477. uint size = (uint)list.Count;
  478. WriteRawVarint32(size);
  479. foreach (var value in list)
  480. {
  481. WriteBool(value);
  482. }
  483. }
  484. public void WritePackedInt32Array(RepeatedField<int> list)
  485. {
  486. uint size = list.CalculateSize(ComputeInt32Size);
  487. WriteRawVarint32(size);
  488. foreach (var value in list)
  489. {
  490. WriteInt32(value);
  491. }
  492. }
  493. public void WritePackedSInt32Array(RepeatedField<int> list)
  494. {
  495. uint size = list.CalculateSize(ComputeSInt32Size);
  496. WriteRawVarint32(size);
  497. foreach (var value in list)
  498. {
  499. WriteSInt32(value);
  500. }
  501. }
  502. public void WritePackedUInt32Array(RepeatedField<uint> list)
  503. {
  504. uint size = list.CalculateSize(ComputeUInt32Size);
  505. WriteRawVarint32(size);
  506. foreach (var value in list)
  507. {
  508. WriteUInt32(value);
  509. }
  510. }
  511. public void WritePackedFixed32Array(RepeatedField<uint> list)
  512. {
  513. uint size = (uint) list.Count * 4;
  514. WriteRawVarint32(size);
  515. foreach (var value in list)
  516. {
  517. WriteFixed32(value);
  518. }
  519. }
  520. public void WritePackedSFixed32Array(RepeatedField<int> list)
  521. {
  522. uint size = (uint) list.Count * 4;
  523. WriteRawVarint32(size);
  524. foreach (var value in list)
  525. {
  526. WriteSFixed32(value);
  527. }
  528. }
  529. public void WritePackedInt64Array(RepeatedField<long> list)
  530. {
  531. uint size = list.CalculateSize(ComputeInt64Size);
  532. WriteRawVarint32(size);
  533. foreach (var value in list)
  534. {
  535. WriteInt64(value);
  536. }
  537. }
  538. public void WritePackedSInt64Array(RepeatedField<long> list)
  539. {
  540. uint size = list.CalculateSize(ComputeSInt64Size);
  541. WriteRawVarint32(size);
  542. foreach (var value in list)
  543. {
  544. WriteSInt64(value);
  545. }
  546. }
  547. public void WritePackedUInt64Array(RepeatedField<ulong> list)
  548. {
  549. if (list.Count == 0)
  550. {
  551. return;
  552. }
  553. uint size = list.CalculateSize(ComputeUInt64Size);
  554. WriteRawVarint32(size);
  555. foreach (var value in list)
  556. {
  557. WriteUInt64(value);
  558. }
  559. }
  560. public void WritePackedFixed64Array(RepeatedField<ulong> list)
  561. {
  562. uint size = (uint) list.Count * 8;
  563. WriteRawVarint32(size);
  564. foreach (var value in list)
  565. {
  566. WriteFixed64(value);
  567. }
  568. }
  569. public void WritePackedSFixed64Array(RepeatedField<long> list)
  570. {
  571. uint size = (uint) list.Count * 8;
  572. WriteRawVarint32(size);
  573. foreach (var value in list)
  574. {
  575. WriteSFixed64(value);
  576. }
  577. }
  578. public void WritePackedDoubleArray(RepeatedField<double> list)
  579. {
  580. uint size = (uint) list.Count * 8;
  581. WriteRawVarint32(size);
  582. foreach (var value in list)
  583. {
  584. WriteDouble(value);
  585. }
  586. }
  587. public void WritePackedFloatArray(RepeatedField<float> list)
  588. {
  589. if (list.Count == 0)
  590. {
  591. return;
  592. }
  593. uint size = (uint) list.Count * 4;
  594. WriteRawVarint32(size);
  595. foreach (var value in list)
  596. {
  597. WriteFloat(value);
  598. }
  599. }
  600. public void WritePackedEnumArray<T>(RepeatedField<T> list)
  601. where T : struct, IComparable, IFormattable
  602. {
  603. if (list.Count == 0)
  604. {
  605. return;
  606. }
  607. // Bit of a hack, to access the values as ints
  608. var iterator = list.GetInt32Enumerator();
  609. uint size = 0;
  610. while (iterator.MoveNext())
  611. {
  612. size += (uint) ComputeEnumSize(iterator.Current);
  613. }
  614. iterator.Reset();
  615. WriteRawVarint32(size);
  616. while (iterator.MoveNext())
  617. {
  618. WriteEnum(iterator.Current);
  619. }
  620. }
  621. #endregion
  622. #region Underlying writing primitives
  623. /// <summary>
  624. /// Writes a 32 bit value as a varint. The fast route is taken when
  625. /// there's enough buffer space left to whizz through without checking
  626. /// for each byte; otherwise, we resort to calling WriteRawByte each time.
  627. /// </summary>
  628. public void WriteRawVarint32(uint value)
  629. {
  630. // Optimize for the common case of a single byte value
  631. if (value < 128 && position < limit)
  632. {
  633. buffer[position++] = (byte)value;
  634. return;
  635. }
  636. while (value > 127 && position < limit)
  637. {
  638. buffer[position++] = (byte) ((value & 0x7F) | 0x80);
  639. value >>= 7;
  640. }
  641. while (value > 127)
  642. {
  643. WriteRawByte((byte) ((value & 0x7F) | 0x80));
  644. value >>= 7;
  645. }
  646. if (position < limit)
  647. {
  648. buffer[position++] = (byte) value;
  649. }
  650. else
  651. {
  652. WriteRawByte((byte) value);
  653. }
  654. }
  655. public void WriteRawVarint64(ulong value)
  656. {
  657. while (value > 127 && position < limit)
  658. {
  659. buffer[position++] = (byte) ((value & 0x7F) | 0x80);
  660. value >>= 7;
  661. }
  662. while (value > 127)
  663. {
  664. WriteRawByte((byte) ((value & 0x7F) | 0x80));
  665. value >>= 7;
  666. }
  667. if (position < limit)
  668. {
  669. buffer[position++] = (byte) value;
  670. }
  671. else
  672. {
  673. WriteRawByte((byte) value);
  674. }
  675. }
  676. public void WriteRawLittleEndian32(uint value)
  677. {
  678. if (position + 4 > limit)
  679. {
  680. WriteRawByte((byte) value);
  681. WriteRawByte((byte) (value >> 8));
  682. WriteRawByte((byte) (value >> 16));
  683. WriteRawByte((byte) (value >> 24));
  684. }
  685. else
  686. {
  687. buffer[position++] = ((byte) value);
  688. buffer[position++] = ((byte) (value >> 8));
  689. buffer[position++] = ((byte) (value >> 16));
  690. buffer[position++] = ((byte) (value >> 24));
  691. }
  692. }
  693. public void WriteRawLittleEndian64(ulong value)
  694. {
  695. if (position + 8 > limit)
  696. {
  697. WriteRawByte((byte) value);
  698. WriteRawByte((byte) (value >> 8));
  699. WriteRawByte((byte) (value >> 16));
  700. WriteRawByte((byte) (value >> 24));
  701. WriteRawByte((byte) (value >> 32));
  702. WriteRawByte((byte) (value >> 40));
  703. WriteRawByte((byte) (value >> 48));
  704. WriteRawByte((byte) (value >> 56));
  705. }
  706. else
  707. {
  708. buffer[position++] = ((byte) value);
  709. buffer[position++] = ((byte) (value >> 8));
  710. buffer[position++] = ((byte) (value >> 16));
  711. buffer[position++] = ((byte) (value >> 24));
  712. buffer[position++] = ((byte) (value >> 32));
  713. buffer[position++] = ((byte) (value >> 40));
  714. buffer[position++] = ((byte) (value >> 48));
  715. buffer[position++] = ((byte) (value >> 56));
  716. }
  717. }
  718. public void WriteRawByte(byte value)
  719. {
  720. if (position == limit)
  721. {
  722. RefreshBuffer();
  723. }
  724. buffer[position++] = value;
  725. }
  726. public void WriteRawByte(uint value)
  727. {
  728. WriteRawByte((byte) value);
  729. }
  730. /// <summary>
  731. /// Writes out an array of bytes.
  732. /// </summary>
  733. public void WriteRawBytes(byte[] value)
  734. {
  735. WriteRawBytes(value, 0, value.Length);
  736. }
  737. /// <summary>
  738. /// Writes out part of an array of bytes.
  739. /// </summary>
  740. public void WriteRawBytes(byte[] value, int offset, int length)
  741. {
  742. if (limit - position >= length)
  743. {
  744. ByteArray.Copy(value, offset, buffer, position, length);
  745. // We have room in the current buffer.
  746. position += length;
  747. }
  748. else
  749. {
  750. // Write extends past current buffer. Fill the rest of this buffer and
  751. // flush.
  752. int bytesWritten = limit - position;
  753. ByteArray.Copy(value, offset, buffer, position, bytesWritten);
  754. offset += bytesWritten;
  755. length -= bytesWritten;
  756. position = limit;
  757. RefreshBuffer();
  758. // Now deal with the rest.
  759. // Since we have an output stream, this is our buffer
  760. // and buffer offset == 0
  761. if (length <= limit)
  762. {
  763. // Fits in new buffer.
  764. ByteArray.Copy(value, offset, buffer, 0, length);
  765. position = length;
  766. }
  767. else
  768. {
  769. // Write is very big. Let's do it all at once.
  770. output.Write(value, offset, length);
  771. }
  772. }
  773. }
  774. #endregion
  775. /// <summary>
  776. /// Encode a 32-bit value with ZigZag encoding.
  777. /// </summary>
  778. /// <remarks>
  779. /// ZigZag encodes signed integers into values that can be efficiently
  780. /// encoded with varint. (Otherwise, negative values must be
  781. /// sign-extended to 64 bits to be varint encoded, thus always taking
  782. /// 10 bytes on the wire.)
  783. /// </remarks>
  784. public static uint EncodeZigZag32(int n)
  785. {
  786. // Note: the right-shift must be arithmetic
  787. return (uint) ((n << 1) ^ (n >> 31));
  788. }
  789. /// <summary>
  790. /// Encode a 64-bit value with ZigZag encoding.
  791. /// </summary>
  792. /// <remarks>
  793. /// ZigZag encodes signed integers into values that can be efficiently
  794. /// encoded with varint. (Otherwise, negative values must be
  795. /// sign-extended to 64 bits to be varint encoded, thus always taking
  796. /// 10 bytes on the wire.)
  797. /// </remarks>
  798. public static ulong EncodeZigZag64(long n)
  799. {
  800. return (ulong) ((n << 1) ^ (n >> 63));
  801. }
  802. private void RefreshBuffer()
  803. {
  804. if (output == null)
  805. {
  806. // We're writing to a single buffer.
  807. throw new OutOfSpaceException();
  808. }
  809. // Since we have an output stream, this is our buffer
  810. // and buffer offset == 0
  811. output.Write(buffer, 0, position);
  812. position = 0;
  813. }
  814. /// <summary>
  815. /// Indicates that a CodedOutputStream wrapping a flat byte array
  816. /// ran out of space.
  817. /// </summary>
  818. public sealed class OutOfSpaceException : IOException
  819. {
  820. internal OutOfSpaceException()
  821. : base("CodedOutputStream was writing to a flat byte array and ran out of space.")
  822. {
  823. }
  824. }
  825. public void Flush()
  826. {
  827. if (output != null)
  828. {
  829. RefreshBuffer();
  830. }
  831. }
  832. /// <summary>
  833. /// Verifies that SpaceLeft returns zero. It's common to create a byte array
  834. /// that is exactly big enough to hold a message, then write to it with
  835. /// a CodedOutputStream. Calling CheckNoSpaceLeft after writing verifies that
  836. /// the message was actually as big as expected, which can help bugs.
  837. /// </summary>
  838. public void CheckNoSpaceLeft()
  839. {
  840. if (SpaceLeft != 0)
  841. {
  842. throw new InvalidOperationException("Did not write as much data as expected.");
  843. }
  844. }
  845. /// <summary>
  846. /// If writing to a flat array, returns the space left in the array. Otherwise,
  847. /// throws an InvalidOperationException.
  848. /// </summary>
  849. public int SpaceLeft
  850. {
  851. get
  852. {
  853. if (output == null)
  854. {
  855. return limit - position;
  856. }
  857. else
  858. {
  859. throw new InvalidOperationException(
  860. "SpaceLeft can only be called on CodedOutputStreams that are " +
  861. "writing to a flat array.");
  862. }
  863. }
  864. }
  865. }
  866. }