CodedOutputStream.cs 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765
  1. // Protocol Buffers - Google's data interchange format
  2. // Copyright 2008 Google Inc.
  3. // http://code.google.com/p/protobuf/
  4. //
  5. // Licensed under the Apache License, Version 2.0 (the "License");
  6. // you may not use this file except in compliance with the License.
  7. // You may obtain a copy of the License at
  8. //
  9. // http://www.apache.org/licenses/LICENSE-2.0
  10. //
  11. // Unless required by applicable law or agreed to in writing, software
  12. // distributed under the License is distributed on an "AS IS" BASIS,
  13. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. // See the License for the specific language governing permissions and
  15. // limitations under the License.
  16. using System;
  17. using System.IO;
  18. using System.Text;
  19. using Google.ProtocolBuffers.Descriptors;
  20. namespace Google.ProtocolBuffers {
  21. /// <summary>
  22. /// Encodes and writes protocol message fields.
  23. /// </summary>
  24. /// <remarks>
  25. /// This class contains two kinds of methods: methods that write specific
  26. /// protocol message constructs and field types (e.g. WriteTag and
  27. /// WriteInt32) and methods that write low-level values (e.g.
  28. /// WriteRawVarint32 and WriteRawBytes). If you are writing encoded protocol
  29. /// messages, you should use the former methods, but if you are writing some
  30. /// other format of your own design, use the latter. The names of the former
  31. /// methods are taken from the protocol buffer type names, not .NET types.
  32. /// (Hence WriteFloat instead of WriteSingle, and WriteBool instead of WriteBoolean.)
  33. /// </remarks>
  34. public sealed class CodedOutputStream {
  35. /// <summary>
  36. /// The buffer size used by CreateInstance(Stream).
  37. /// </summary>
  38. public static readonly int DefaultBufferSize = 4096;
  39. private readonly byte[] buffer;
  40. private readonly int limit;
  41. private int position;
  42. private readonly Stream output;
  43. #region Construction
  44. private CodedOutputStream(byte[] buffer, int offset, int length) {
  45. this.output = null;
  46. this.buffer = buffer;
  47. this.position = offset;
  48. this.limit = offset + length;
  49. }
  50. private CodedOutputStream(Stream output, byte[] buffer) {
  51. this.output = output;
  52. this.buffer = buffer;
  53. this.position = 0;
  54. this.limit = buffer.Length;
  55. }
  56. /// <summary>
  57. /// Creates a new CodedOutputStream which write to the given stream.
  58. /// </summary>
  59. public static CodedOutputStream CreateInstance(Stream output) {
  60. return CreateInstance(output, DefaultBufferSize);
  61. }
  62. /// <summary>
  63. /// Creates a new CodedOutputStream which write to the given stream and uses
  64. /// the specified buffer size.
  65. /// </summary>
  66. public static CodedOutputStream CreateInstance(Stream output, int bufferSize) {
  67. return new CodedOutputStream(output, new byte[bufferSize]);
  68. }
  69. /// <summary>
  70. /// Creates a new CodedOutputStream that writes directly to the given
  71. /// byte array. If more bytes are written than fit in the array,
  72. /// OutOfSpaceException will be thrown.
  73. /// </summary>
  74. public static CodedOutputStream CreateInstance(byte[] flatArray) {
  75. return CreateInstance(flatArray, 0, flatArray.Length);
  76. }
  77. /// <summary>
  78. /// Creates a new CodedOutputStream that writes directly to the given
  79. /// byte array slice. If more bytes are written than fit in the array,
  80. /// OutOfSpaceException will be thrown.
  81. /// </summary>
  82. public static CodedOutputStream CreateInstance(byte[] flatArray, int offset, int length) {
  83. return new CodedOutputStream(flatArray, offset, length);
  84. }
  85. #endregion
  86. #region Writing of tags etc
  87. /// <summary>
  88. /// Writes a double field value, including tag, to the stream.
  89. /// </summary>
  90. public void WriteDouble(int fieldNumber, double value) {
  91. // TODO(jonskeet): Test this on different endiannesses
  92. WriteTag(fieldNumber, WireFormat.WireType.Fixed64);
  93. WriteRawLittleEndian64((ulong)BitConverter.DoubleToInt64Bits(value));
  94. }
  95. /// <summary>
  96. /// Writes a float field value, including tag, to the stream.
  97. /// </summary>
  98. public void WriteFloat(int fieldNumber, float value) {
  99. WriteTag(fieldNumber, WireFormat.WireType.Fixed32);
  100. // TODO(jonskeet): Test this on different endiannesses
  101. byte[] rawBytes = BitConverter.GetBytes(value);
  102. uint asInteger = BitConverter.ToUInt32(rawBytes, 0);
  103. WriteRawLittleEndian32(asInteger);
  104. }
  105. /// <summary>
  106. /// Writes a uint64 field value, including tag, to the stream.
  107. /// </summary>
  108. public void WriteUInt64(int fieldNumber, ulong value) {
  109. WriteTag(fieldNumber, WireFormat.WireType.Varint);
  110. WriteRawVarint64(value);
  111. }
  112. /// <summary>
  113. /// Writes an int64 field value, including tag, to the stream.
  114. /// </summary>
  115. public void WriteInt64(int fieldNumber, long value) {
  116. WriteTag(fieldNumber, WireFormat.WireType.Varint);
  117. WriteRawVarint64((ulong)value);
  118. }
  119. /// <summary>
  120. /// Writes an int32 field value, including tag, to the stream.
  121. /// </summary>
  122. public void WriteInt32(int fieldNumber, int value) {
  123. WriteTag(fieldNumber, WireFormat.WireType.Varint);
  124. if (value >= 0) {
  125. WriteRawVarint32((uint)value);
  126. } else {
  127. // Must sign-extend.
  128. WriteRawVarint64((ulong)value);
  129. }
  130. }
  131. /// <summary>
  132. /// Writes a fixed64 field value, including tag, to the stream.
  133. /// </summary>
  134. public void WriteFixed64(int fieldNumber, ulong value) {
  135. WriteTag(fieldNumber, WireFormat.WireType.Fixed64);
  136. WriteRawLittleEndian64(value);
  137. }
  138. /// <summary>
  139. /// Writes a fixed32 field value, including tag, to the stream.
  140. /// </summary>
  141. public void WriteFixed32(int fieldNumber, uint value) {
  142. WriteTag(fieldNumber, WireFormat.WireType.Fixed32);
  143. WriteRawLittleEndian32(value);
  144. }
  145. /// <summary>
  146. /// Writes a bool field value, including tag, to the stream.
  147. /// </summary>
  148. public void WriteBool(int fieldNumber, bool value) {
  149. WriteTag(fieldNumber, WireFormat.WireType.Varint);
  150. WriteRawByte(value ? (byte)1 : (byte)0);
  151. }
  152. /// <summary>
  153. /// Writes a string field value, including tag, to the stream.
  154. /// </summary>
  155. public void WriteString(int fieldNumber, string value) {
  156. WriteTag(fieldNumber, WireFormat.WireType.LengthDelimited);
  157. // Optimise the case where we have enough space to write
  158. // the string directly to the buffer, which should be common.
  159. int length = Encoding.UTF8.GetByteCount(value);
  160. WriteRawVarint32((uint) length);
  161. if (limit - position >= length) {
  162. Encoding.UTF8.GetBytes(value, 0, value.Length, buffer, position);
  163. position += length;
  164. } else {
  165. byte[] bytes = Encoding.UTF8.GetBytes(value);
  166. WriteRawBytes(bytes);
  167. }
  168. }
  169. /// <summary>
  170. /// Writes a group field value, including tag, to the stream.
  171. /// </summary>
  172. public void WriteGroup(int fieldNumber, IMessage value) {
  173. WriteTag(fieldNumber, WireFormat.WireType.StartGroup);
  174. value.WriteTo(this);
  175. WriteTag(fieldNumber, WireFormat.WireType.EndGroup);
  176. }
  177. public void WriteUnknownGroup(int fieldNumber, UnknownFieldSet value) {
  178. WriteTag(fieldNumber, WireFormat.WireType.StartGroup);
  179. value.WriteTo(this);
  180. WriteTag(fieldNumber, WireFormat.WireType.EndGroup);
  181. }
  182. public void WriteMessage(int fieldNumber, IMessage value) {
  183. WriteTag(fieldNumber, WireFormat.WireType.LengthDelimited);
  184. WriteRawVarint32((uint)value.SerializedSize);
  185. value.WriteTo(this);
  186. }
  187. public void WriteBytes(int fieldNumber, ByteString value) {
  188. // TODO(jonskeet): Optimise this! (No need to copy the bytes twice.)
  189. WriteTag(fieldNumber, WireFormat.WireType.LengthDelimited);
  190. byte[] bytes = value.ToByteArray();
  191. WriteRawVarint32((uint)bytes.Length);
  192. WriteRawBytes(bytes);
  193. }
  194. public void WriteUInt32(int fieldNumber, uint value) {
  195. WriteTag(fieldNumber, WireFormat.WireType.Varint);
  196. WriteRawVarint32(value);
  197. }
  198. public void WriteEnum(int fieldNumber, int value) {
  199. WriteTag(fieldNumber, WireFormat.WireType.Varint);
  200. WriteRawVarint32((uint)value);
  201. }
  202. public void WriteSFixed32(int fieldNumber, int value) {
  203. WriteTag(fieldNumber, WireFormat.WireType.Fixed32);
  204. WriteRawLittleEndian32((uint)value);
  205. }
  206. public void WriteSFixed64(int fieldNumber, long value) {
  207. WriteTag(fieldNumber, WireFormat.WireType.Fixed64);
  208. WriteRawLittleEndian64((ulong)value);
  209. }
  210. public void WriteSInt32(int fieldNumber, int value) {
  211. WriteTag(fieldNumber, WireFormat.WireType.Varint);
  212. WriteRawVarint32(EncodeZigZag32(value));
  213. }
  214. public void WriteSInt64(int fieldNumber, long value) {
  215. WriteTag(fieldNumber, WireFormat.WireType.Varint);
  216. WriteRawVarint64(EncodeZigZag64(value));
  217. }
  218. public void WriteMessageSetExtension(int fieldNumber, IMessage value) {
  219. WriteTag(WireFormat.MessageSetField.Item, WireFormat.WireType.StartGroup);
  220. WriteUInt32(WireFormat.MessageSetField.TypeID, (uint)fieldNumber);
  221. WriteMessage(WireFormat.MessageSetField.Message, value);
  222. WriteTag(WireFormat.MessageSetField.Item, WireFormat.WireType.EndGroup);
  223. }
  224. public void WriteRawMessageSetExtension(int fieldNumber, ByteString value) {
  225. WriteTag(WireFormat.MessageSetField.Item, WireFormat.WireType.StartGroup);
  226. WriteUInt32(WireFormat.MessageSetField.TypeID, (uint)fieldNumber);
  227. WriteBytes(WireFormat.MessageSetField.Message, value);
  228. WriteTag(WireFormat.MessageSetField.Item, WireFormat.WireType.EndGroup);
  229. }
  230. public void WriteField(FieldType fieldType, int fieldNumber, object value) {
  231. switch (fieldType) {
  232. case FieldType.Double: WriteDouble(fieldNumber, (double)value); break;
  233. case FieldType.Float: WriteFloat(fieldNumber, (float)value); break;
  234. case FieldType.Int64: WriteInt64(fieldNumber, (long)value); break;
  235. case FieldType.UInt64: WriteUInt64(fieldNumber, (ulong)value); break;
  236. case FieldType.Int32: WriteInt32(fieldNumber, (int)value); break;
  237. case FieldType.Fixed64: WriteFixed64(fieldNumber, (ulong)value); break;
  238. case FieldType.Fixed32: WriteFixed32(fieldNumber, (uint)value); break;
  239. case FieldType.Bool: WriteBool(fieldNumber, (bool)value); break;
  240. case FieldType.String: WriteString(fieldNumber, (string)value); break;
  241. case FieldType.Group: WriteGroup(fieldNumber, (IMessage)value); break;
  242. case FieldType.Message: WriteMessage(fieldNumber, (IMessage)value); break;
  243. case FieldType.Bytes: WriteBytes(fieldNumber, (ByteString)value); break;
  244. case FieldType.UInt32: WriteUInt32(fieldNumber, (uint)value); break;
  245. case FieldType.SFixed32: WriteSFixed32(fieldNumber, (int)value); break;
  246. case FieldType.SFixed64: WriteSFixed64(fieldNumber, (long)value); break;
  247. case FieldType.SInt32: WriteSInt32(fieldNumber, (int)value); break;
  248. case FieldType.SInt64: WriteSInt64(fieldNumber, (long)value); break;
  249. case FieldType.Enum: WriteEnum(fieldNumber, ((EnumValueDescriptor)value).Number);
  250. break;
  251. }
  252. }
  253. #endregion
  254. #region Underlying writing primitives
  255. /// <summary>
  256. /// Encodes and writes a tag.
  257. /// </summary>
  258. public void WriteTag(int fieldNumber, WireFormat.WireType type) {
  259. WriteRawVarint32(WireFormat.MakeTag(fieldNumber, type));
  260. }
  261. private void SlowWriteRawVarint32(uint value) {
  262. while (true) {
  263. if ((value & ~0x7F) == 0) {
  264. WriteRawByte(value);
  265. return;
  266. } else {
  267. WriteRawByte((value & 0x7F) | 0x80);
  268. value >>= 7;
  269. }
  270. }
  271. }
  272. /// <summary>
  273. /// Writes a 32 bit value as a varint. The fast route is taken when
  274. /// there's enough buffer space left to whizz through without checking
  275. /// for each byte; otherwise, we resort to calling WriteRawByte each time.
  276. /// </summary>
  277. public void WriteRawVarint32(uint value) {
  278. if (position + 5 > limit) {
  279. SlowWriteRawVarint32(value);
  280. return;
  281. }
  282. while (true) {
  283. if ((value & ~0x7F) == 0) {
  284. buffer[position++] = (byte) value;
  285. return;
  286. } else {
  287. buffer[position++] = (byte)((value & 0x7F) | 0x80);
  288. value >>= 7;
  289. }
  290. }
  291. }
  292. public void WriteRawVarint64(ulong value) {
  293. while (true) {
  294. if ((value & ~0x7FUL) == 0) {
  295. WriteRawByte((uint)value);
  296. return;
  297. } else {
  298. WriteRawByte(((uint)value & 0x7F) | 0x80);
  299. value >>= 7;
  300. }
  301. }
  302. }
  303. public void WriteRawLittleEndian32(uint value) {
  304. WriteRawByte((byte)value);
  305. WriteRawByte((byte)(value >> 8));
  306. WriteRawByte((byte)(value >> 16));
  307. WriteRawByte((byte)(value >> 24));
  308. }
  309. public void WriteRawLittleEndian64(ulong value) {
  310. WriteRawByte((byte)value);
  311. WriteRawByte((byte)(value >> 8));
  312. WriteRawByte((byte)(value >> 16));
  313. WriteRawByte((byte)(value >> 24));
  314. WriteRawByte((byte)(value >> 32));
  315. WriteRawByte((byte)(value >> 40));
  316. WriteRawByte((byte)(value >> 48));
  317. WriteRawByte((byte)(value >> 56));
  318. }
  319. public void WriteRawByte(byte value) {
  320. if (position == limit) {
  321. RefreshBuffer();
  322. }
  323. buffer[position++] = value;
  324. }
  325. public void WriteRawByte(uint value) {
  326. WriteRawByte((byte)value);
  327. }
  328. /// <summary>
  329. /// Writes out an array of bytes.
  330. /// </summary>
  331. public void WriteRawBytes(byte[] value) {
  332. WriteRawBytes(value, 0, value.Length);
  333. }
  334. /// <summary>
  335. /// Writes out part of an array of bytes.
  336. /// </summary>
  337. public void WriteRawBytes(byte[] value, int offset, int length) {
  338. if (limit - position >= length) {
  339. Array.Copy(value, offset, buffer, position, length);
  340. // We have room in the current buffer.
  341. position += length;
  342. } else {
  343. // Write extends past current buffer. Fill the rest of this buffer and
  344. // flush.
  345. int bytesWritten = limit - position;
  346. Array.Copy(value, offset, buffer, position, bytesWritten);
  347. offset += bytesWritten;
  348. length -= bytesWritten;
  349. position = limit;
  350. RefreshBuffer();
  351. // Now deal with the rest.
  352. // Since we have an output stream, this is our buffer
  353. // and buffer offset == 0
  354. if (length <= limit) {
  355. // Fits in new buffer.
  356. Array.Copy(value, offset, buffer, 0, length);
  357. position = length;
  358. } else {
  359. // Write is very big. Let's do it all at once.
  360. output.Write(value, offset, length);
  361. }
  362. }
  363. }
  364. #endregion
  365. #region Size computations
  366. const int LittleEndian64Size = 8;
  367. const int LittleEndian32Size = 4;
  368. /// <summary>
  369. /// Compute the number of bytes that would be needed to encode a
  370. /// double field, including the tag.
  371. /// </summary>
  372. public static int ComputeDoubleSize(int fieldNumber, double value) {
  373. return ComputeTagSize(fieldNumber) + LittleEndian64Size;
  374. }
  375. /// <summary>
  376. /// Compute the number of bytes that would be needed to encode a
  377. /// float field, including the tag.
  378. /// </summary>
  379. public static int ComputeFloatSize(int fieldNumber, float value) {
  380. return ComputeTagSize(fieldNumber) + LittleEndian32Size;
  381. }
  382. /// <summary>
  383. /// Compute the number of bytes that would be needed to encode a
  384. /// uint64 field, including the tag.
  385. /// </summary>
  386. public static int ComputeUInt64Size(int fieldNumber, ulong value) {
  387. return ComputeTagSize(fieldNumber) + ComputeRawVarint64Size(value);
  388. }
  389. /// <summary>
  390. /// Compute the number of bytes that would be needed to encode an
  391. /// int64 field, including the tag.
  392. /// </summary>
  393. public static int ComputeInt64Size(int fieldNumber, long value) {
  394. return ComputeTagSize(fieldNumber) + ComputeRawVarint64Size((ulong)value);
  395. }
  396. /// <summary>
  397. /// Compute the number of bytes that would be needed to encode an
  398. /// int32 field, including the tag.
  399. /// </summary>
  400. public static int ComputeInt32Size(int fieldNumber, int value) {
  401. if (value >= 0) {
  402. return ComputeTagSize(fieldNumber) + ComputeRawVarint32Size((uint)value);
  403. } else {
  404. // Must sign-extend.
  405. return ComputeTagSize(fieldNumber) + 10;
  406. }
  407. }
  408. /// <summary>
  409. /// Compute the number of bytes that would be needed to encode a
  410. /// fixed64 field, including the tag.
  411. /// </summary>
  412. public static int ComputeFixed64Size(int fieldNumber, ulong value) {
  413. return ComputeTagSize(fieldNumber) + LittleEndian64Size;
  414. }
  415. /// <summary>
  416. /// Compute the number of bytes that would be needed to encode a
  417. /// fixed32 field, including the tag.
  418. /// </summary>
  419. public static int ComputeFixed32Size(int fieldNumber, uint value) {
  420. return ComputeTagSize(fieldNumber) + LittleEndian32Size;
  421. }
  422. /// <summary>
  423. /// Compute the number of bytes that would be needed to encode a
  424. /// bool field, including the tag.
  425. /// </summary>
  426. public static int ComputeBoolSize(int fieldNumber, bool value) {
  427. return ComputeTagSize(fieldNumber) + 1;
  428. }
  429. /// <summary>
  430. /// Compute the number of bytes that would be needed to encode a
  431. /// string field, including the tag.
  432. /// </summary>
  433. public static int ComputeStringSize(int fieldNumber, String value) {
  434. int byteArraySize = Encoding.UTF8.GetByteCount(value);
  435. return ComputeTagSize(fieldNumber) +
  436. ComputeRawVarint32Size((uint)byteArraySize) +
  437. byteArraySize;
  438. }
  439. /// <summary>
  440. /// Compute the number of bytes that would be needed to encode a
  441. /// group field, including the tag.
  442. /// </summary>
  443. public static int ComputeGroupSize(int fieldNumber, IMessage value) {
  444. return ComputeTagSize(fieldNumber) * 2 + value.SerializedSize;
  445. }
  446. /// <summary>
  447. /// Compute the number of bytes that would be needed to encode a
  448. /// group field represented by an UnknownFieldSet, including the tag.
  449. /// </summary>
  450. public static int ComputeUnknownGroupSize(int fieldNumber,
  451. UnknownFieldSet value) {
  452. return ComputeTagSize(fieldNumber) * 2 + value.SerializedSize;
  453. }
  454. /// <summary>
  455. /// Compute the number of bytes that would be needed to encode an
  456. /// embedded message field, including the tag.
  457. /// </summary>
  458. public static int ComputeMessageSize(int fieldNumber, IMessage value) {
  459. int size = value.SerializedSize;
  460. return ComputeTagSize(fieldNumber) + ComputeRawVarint32Size((uint)size) + size;
  461. }
  462. /// <summary>
  463. /// Compute the number of bytes that would be needed to encode a
  464. /// bytes field, including the tag.
  465. /// </summary>
  466. public static int ComputeBytesSize(int fieldNumber, ByteString value) {
  467. return ComputeTagSize(fieldNumber) +
  468. ComputeRawVarint32Size((uint)value.Length) +
  469. value.Length;
  470. }
  471. /// <summary>
  472. /// Compute the number of bytes that would be needed to encode a
  473. /// uint32 field, including the tag.
  474. /// </summary>
  475. public static int ComputeUInt32Size(int fieldNumber, uint value) {
  476. return ComputeTagSize(fieldNumber) + ComputeRawVarint32Size(value);
  477. }
  478. /// <summary>
  479. /// Compute the number of bytes that would be needed to encode a
  480. /// enum field, including the tag. The caller is responsible for
  481. /// converting the enum value to its numeric value.
  482. /// </summary>
  483. public static int ComputeEnumSize(int fieldNumber, int value) {
  484. return ComputeTagSize(fieldNumber) + ComputeRawVarint32Size((uint)value);
  485. }
  486. /// <summary>
  487. /// Compute the number of bytes that would be needed to encode an
  488. /// sfixed32 field, including the tag.
  489. /// </summary>
  490. public static int ComputeSFixed32Size(int fieldNumber, int value) {
  491. return ComputeTagSize(fieldNumber) + LittleEndian32Size;
  492. }
  493. /// <summary>
  494. /// Compute the number of bytes that would be needed to encode an
  495. /// sfixed64 field, including the tag.
  496. /// </summary>
  497. public static int ComputeSFixed64Size(int fieldNumber, long value) {
  498. return ComputeTagSize(fieldNumber) + LittleEndian64Size;
  499. }
  500. /// <summary>
  501. /// Compute the number of bytes that would be needed to encode an
  502. /// sint32 field, including the tag.
  503. /// </summary>
  504. public static int ComputeSInt32Size(int fieldNumber, int value) {
  505. return ComputeTagSize(fieldNumber) +
  506. ComputeRawVarint32Size(EncodeZigZag32(value));
  507. }
  508. /// <summary>
  509. /// Compute the number of bytes that would be needed to encode an
  510. /// sint64 field, including the tag.
  511. /// </summary>
  512. public static int ComputeSInt64Size(int fieldNumber, long value) {
  513. return ComputeTagSize(fieldNumber) +
  514. ComputeRawVarint64Size(EncodeZigZag64(value));
  515. }
  516. /*
  517. * Compute the number of bytes that would be needed to encode a
  518. * MessageSet extension to the stream. For historical reasons,
  519. * the wire format differs from normal fields.
  520. */
  521. /// <summary>
  522. /// Compute the number of bytes that would be needed to encode a
  523. /// MessageSet extension to the stream. For historical reasons,
  524. /// the wire format differs from normal fields.
  525. /// </summary>
  526. public static int ComputeMessageSetExtensionSize(int fieldNumber, IMessage value) {
  527. return ComputeTagSize(WireFormat.MessageSetField.Item) * 2 +
  528. ComputeUInt32Size(WireFormat.MessageSetField.TypeID, (uint) fieldNumber) +
  529. ComputeMessageSize(WireFormat.MessageSetField.Message, value);
  530. }
  531. /// <summary>
  532. /// Compute the number of bytes that would be needed to encode an
  533. /// unparsed MessageSet extension field to the stream. For
  534. /// historical reasons, the wire format differs from normal fields.
  535. /// </summary>
  536. public static int ComputeRawMessageSetExtensionSize(int fieldNumber, ByteString value) {
  537. return ComputeTagSize(WireFormat.MessageSetField.Item) * 2 +
  538. ComputeUInt32Size(WireFormat.MessageSetField.TypeID, (uint) fieldNumber) +
  539. ComputeBytesSize(WireFormat.MessageSetField.Message, value);
  540. }
  541. /// <summary>
  542. /// Compute the number of bytes that would be needed to encode a varint.
  543. /// </summary>
  544. public static int ComputeRawVarint32Size(uint value) {
  545. if ((value & (0xffffffff << 7)) == 0) return 1;
  546. if ((value & (0xffffffff << 14)) == 0) return 2;
  547. if ((value & (0xffffffff << 21)) == 0) return 3;
  548. if ((value & (0xffffffff << 28)) == 0) return 4;
  549. return 5;
  550. }
  551. /// <summary>
  552. /// Compute the number of bytes that would be needed to encode a varint.
  553. /// </summary>
  554. public static int ComputeRawVarint64Size(ulong value) {
  555. if ((value & (0xffffffffffffffffL << 7)) == 0) return 1;
  556. if ((value & (0xffffffffffffffffL << 14)) == 0) return 2;
  557. if ((value & (0xffffffffffffffffL << 21)) == 0) return 3;
  558. if ((value & (0xffffffffffffffffL << 28)) == 0) return 4;
  559. if ((value & (0xffffffffffffffffL << 35)) == 0) return 5;
  560. if ((value & (0xffffffffffffffffL << 42)) == 0) return 6;
  561. if ((value & (0xffffffffffffffffL << 49)) == 0) return 7;
  562. if ((value & (0xffffffffffffffffL << 56)) == 0) return 8;
  563. if ((value & (0xffffffffffffffffL << 63)) == 0) return 9;
  564. return 10;
  565. }
  566. /*
  567. * Compute the number of bytes that would be needed to encode a
  568. * field of arbitrary type, including tag, to the stream.
  569. *
  570. * @param type The field's type.
  571. * @param number The field's number.
  572. * @param value Object representing the field's value. Must be of the exact
  573. * type which would be returned by
  574. * {@link Message#getField(FieldDescriptor)} for
  575. * this field.
  576. */
  577. public static int ComputeFieldSize(FieldType fieldType, int fieldNumber, Object value) {
  578. switch (fieldType) {
  579. case FieldType.Double: return ComputeDoubleSize(fieldNumber, (double)value);
  580. case FieldType.Float: return ComputeFloatSize(fieldNumber, (float)value);
  581. case FieldType.Int64: return ComputeInt64Size(fieldNumber, (long)value);
  582. case FieldType.UInt64: return ComputeUInt64Size(fieldNumber, (ulong)value);
  583. case FieldType.Int32: return ComputeInt32Size(fieldNumber, (int)value);
  584. case FieldType.Fixed64: return ComputeFixed64Size(fieldNumber, (ulong)value);
  585. case FieldType.Fixed32: return ComputeFixed32Size(fieldNumber, (uint)value);
  586. case FieldType.Bool: return ComputeBoolSize(fieldNumber, (bool)value);
  587. case FieldType.String: return ComputeStringSize(fieldNumber, (string)value);
  588. case FieldType.Group: return ComputeGroupSize(fieldNumber, (IMessage)value);
  589. case FieldType.Message: return ComputeMessageSize(fieldNumber, (IMessage)value);
  590. case FieldType.Bytes: return ComputeBytesSize(fieldNumber, (ByteString)value);
  591. case FieldType.UInt32: return ComputeUInt32Size(fieldNumber, (uint)value);
  592. case FieldType.SFixed32: return ComputeSFixed32Size(fieldNumber, (int)value);
  593. case FieldType.SFixed64: return ComputeSFixed64Size(fieldNumber, (long)value);
  594. case FieldType.SInt32: return ComputeSInt32Size(fieldNumber, (int)value);
  595. case FieldType.SInt64: return ComputeSInt64Size(fieldNumber, (long)value);
  596. case FieldType.Enum: return ComputeEnumSize(fieldNumber, ((EnumValueDescriptor)value).Number);
  597. default:
  598. throw new ArgumentOutOfRangeException("Invalid field type " + fieldType);
  599. }
  600. }
  601. /// <summary>
  602. /// Compute the number of bytes that would be needed to encode a tag.
  603. /// </summary>
  604. public static int ComputeTagSize(int fieldNumber) {
  605. return ComputeRawVarint32Size(WireFormat.MakeTag(fieldNumber, 0));
  606. }
  607. #endregion
  608. /// <summary>
  609. /// Encode a 32-bit value with ZigZag encoding.
  610. /// </summary>
  611. /// <remarks>
  612. /// ZigZag encodes signed integers into values that can be efficiently
  613. /// encoded with varint. (Otherwise, negative values must be
  614. /// sign-extended to 64 bits to be varint encoded, thus always taking
  615. /// 10 bytes on the wire.)
  616. /// </remarks>
  617. public static uint EncodeZigZag32(int n) {
  618. // Note: the right-shift must be arithmetic
  619. return (uint)((n << 1) ^ (n >> 31));
  620. }
  621. /// <summary>
  622. /// Encode a 64-bit value with ZigZag encoding.
  623. /// </summary>
  624. /// <remarks>
  625. /// ZigZag encodes signed integers into values that can be efficiently
  626. /// encoded with varint. (Otherwise, negative values must be
  627. /// sign-extended to 64 bits to be varint encoded, thus always taking
  628. /// 10 bytes on the wire.)
  629. /// </remarks>
  630. public static ulong EncodeZigZag64(long n) {
  631. return (ulong)((n << 1) ^ (n >> 63));
  632. }
  633. private void RefreshBuffer() {
  634. if (output == null) {
  635. // We're writing to a single buffer.
  636. throw new OutOfSpaceException();
  637. }
  638. // Since we have an output stream, this is our buffer
  639. // and buffer offset == 0
  640. output.Write(buffer, 0, position);
  641. position = 0;
  642. }
  643. /// <summary>
  644. /// Indicates that a CodedOutputStream wrapping a flat byte array
  645. /// ran out of space.
  646. /// </summary>
  647. public sealed class OutOfSpaceException : IOException {
  648. internal OutOfSpaceException()
  649. : base("CodedOutputStream was writing to a flat byte array and ran out of space.") {
  650. }
  651. }
  652. public void Flush() {
  653. if (output != null) {
  654. RefreshBuffer();
  655. }
  656. }
  657. /// <summary>
  658. /// Verifies that SpaceLeft returns zero. It's common to create a byte array
  659. /// that is exactly big enough to hold a message, then write to it with
  660. /// a CodedOutputStream. Calling CheckNoSpaceLeft after writing verifies that
  661. /// the message was actually as big as expected, which can help bugs.
  662. /// </summary>
  663. public void CheckNoSpaceLeft() {
  664. if (SpaceLeft != 0) {
  665. throw new InvalidOperationException("Did not write as much data as expected.");
  666. }
  667. }
  668. /// <summary>
  669. /// If writing to a flat array, returns the space left in the array. Otherwise,
  670. /// throws an InvalidOperationException.
  671. /// </summary>
  672. public int SpaceLeft {
  673. get {
  674. if (output == null) {
  675. return limit - position;
  676. } else {
  677. throw new InvalidOperationException(
  678. "SpaceLeft can only be called on CodedOutputStreams that are " +
  679. "writing to a flat array.");
  680. }
  681. }
  682. }
  683. }
  684. }