CodedOutputStream.cs 31 KB

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