CodedOutputStream.cs 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740
  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. // TODO(jonskeet): Optimise this if possible
  158. // Unfortunately there does not appear to be any way to tell Java to encode
  159. // UTF-8 directly into our buffer, so we have to let it create its own byte
  160. // array and then copy. In .NET we can do the same thing very easily,
  161. // so we don't need to worry about only writing one buffer at a time.
  162. // We can optimise later.
  163. byte[] bytes = Encoding.UTF8.GetBytes(value);
  164. WriteRawVarint32((uint)bytes.Length);
  165. WriteRawBytes(bytes);
  166. }
  167. /// <summary>
  168. /// Writes a group field value, including tag, to the stream.
  169. /// </summary>
  170. public void WriteGroup(int fieldNumber, IMessage value) {
  171. WriteTag(fieldNumber, WireFormat.WireType.StartGroup);
  172. value.WriteTo(this);
  173. WriteTag(fieldNumber, WireFormat.WireType.EndGroup);
  174. }
  175. public void WriteUnknownGroup(int fieldNumber, UnknownFieldSet value) {
  176. WriteTag(fieldNumber, WireFormat.WireType.StartGroup);
  177. value.WriteTo(this);
  178. WriteTag(fieldNumber, WireFormat.WireType.EndGroup);
  179. }
  180. public void WriteMessage(int fieldNumber, IMessage value) {
  181. WriteTag(fieldNumber, WireFormat.WireType.LengthDelimited);
  182. WriteRawVarint32((uint)value.SerializedSize);
  183. value.WriteTo(this);
  184. }
  185. public void WriteBytes(int fieldNumber, ByteString value) {
  186. // TODO(jonskeet): Optimise this! (No need to copy the bytes twice.)
  187. byte[] bytes = value.ToByteArray();
  188. WriteRawVarint32((uint)bytes.Length);
  189. WriteRawBytes(bytes);
  190. }
  191. public void WriteUInt32(int fieldNumber, uint value) {
  192. WriteTag(fieldNumber, WireFormat.WireType.Varint);
  193. WriteRawVarint32(value);
  194. }
  195. public void WriteEnum(int fieldNumber, int value) {
  196. WriteTag(fieldNumber, WireFormat.WireType.Varint);
  197. WriteRawVarint32((uint)value);
  198. }
  199. public void WriteSFixed32(int fieldNumber, int value) {
  200. WriteTag(fieldNumber, WireFormat.WireType.Fixed32);
  201. WriteRawVarint32((uint)value);
  202. }
  203. public void WriteSFixed64(int fieldNumber, long value) {
  204. WriteTag(fieldNumber, WireFormat.WireType.Fixed64);
  205. WriteRawVarint64((ulong)value);
  206. }
  207. public void WriteSInt32(int fieldNumber, int value) {
  208. WriteTag(fieldNumber, WireFormat.WireType.Varint);
  209. WriteRawVarint32(EncodeZigZag32(value));
  210. }
  211. public void WriteSInt64(int fieldNumber, long value) {
  212. WriteTag(fieldNumber, WireFormat.WireType.Varint);
  213. WriteRawVarint64(EncodeZigZag64(value));
  214. }
  215. public void WriteMessageSetExtension(int fieldNumber, IMessage value) {
  216. WriteTag(WireFormat.MessageSetField.Item, WireFormat.WireType.StartGroup);
  217. WriteUInt32(WireFormat.MessageSetField.TypeID, (uint)fieldNumber);
  218. WriteMessage(WireFormat.MessageSetField.Message, value);
  219. WriteTag(WireFormat.MessageSetField.Item, WireFormat.WireType.EndGroup);
  220. }
  221. public void WriteRawMessageSetExtension(int fieldNumber, ByteString value) {
  222. WriteTag(WireFormat.MessageSetField.Item, WireFormat.WireType.StartGroup);
  223. WriteUInt32(WireFormat.MessageSetField.TypeID, (uint)fieldNumber);
  224. WriteBytes(WireFormat.MessageSetField.Message, value);
  225. WriteTag(WireFormat.MessageSetField.Item, WireFormat.WireType.EndGroup);
  226. }
  227. public void WriteField(FieldType fieldType, int fieldNumber, object value) {
  228. switch (fieldType) {
  229. case FieldType.Double: WriteDouble(fieldNumber, (double)value); break;
  230. case FieldType.Float: WriteFloat(fieldNumber, (float)value); break;
  231. case FieldType.Int64: WriteInt64(fieldNumber, (long)value); break;
  232. case FieldType.UInt64: WriteUInt64(fieldNumber, (ulong)value); break;
  233. case FieldType.Int32: WriteInt32(fieldNumber, (int)value); break;
  234. case FieldType.Fixed64: WriteFixed64(fieldNumber, (ulong)value); break;
  235. case FieldType.Fixed32: WriteFixed32(fieldNumber, (uint)value); break;
  236. case FieldType.Bool: WriteBool(fieldNumber, (bool)value); break;
  237. case FieldType.String: WriteString(fieldNumber, (string)value); break;
  238. case FieldType.Group: WriteGroup(fieldNumber, (IMessage)value); break;
  239. case FieldType.Message: WriteMessage(fieldNumber, (IMessage)value); break;
  240. case FieldType.Bytes: WriteBytes(fieldNumber, (ByteString)value); break;
  241. case FieldType.UInt32: WriteUInt32(fieldNumber, (uint)value); break;
  242. case FieldType.SFixed32: WriteSFixed32(fieldNumber, (int)value); break;
  243. case FieldType.SFixed64: WriteSFixed64(fieldNumber, (long)value); break;
  244. case FieldType.SInt32: WriteSInt32(fieldNumber, (int)value); break;
  245. case FieldType.SInt64: WriteSInt64(fieldNumber, (long)value); break;
  246. case FieldType.Enum: WriteEnum(fieldNumber, ((EnumValueDescriptor)value).Number);
  247. break;
  248. }
  249. }
  250. #endregion
  251. #region Underlying writing primitives
  252. /// <summary>
  253. /// Encodes and writes a tag.
  254. /// </summary>
  255. public void WriteTag(int fieldNumber, WireFormat.WireType type) {
  256. WriteRawVarint32(WireFormat.MakeTag(fieldNumber, type));
  257. }
  258. public void WriteRawVarint32(uint value) {
  259. while (true) {
  260. if ((value & ~0x7F) == 0) {
  261. WriteRawByte(value);
  262. return;
  263. } else {
  264. WriteRawByte((value & 0x7F) | 0x80);
  265. value >>= 7;
  266. }
  267. }
  268. }
  269. public void WriteRawVarint64(ulong value) {
  270. while (true) {
  271. if ((value & ~0x7FUL) == 0) {
  272. WriteRawByte((uint)value);
  273. return;
  274. } else {
  275. WriteRawByte(((uint)value & 0x7F) | 0x80);
  276. value >>= 7;
  277. }
  278. }
  279. }
  280. public void WriteRawLittleEndian32(uint value) {
  281. WriteRawByte((byte)value);
  282. WriteRawByte((byte)(value >> 8));
  283. WriteRawByte((byte)(value >> 16));
  284. WriteRawByte((byte)(value >> 24));
  285. }
  286. public void WriteRawLittleEndian64(ulong value) {
  287. WriteRawByte((byte)value);
  288. WriteRawByte((byte)(value >> 8));
  289. WriteRawByte((byte)(value >> 16));
  290. WriteRawByte((byte)(value >> 24));
  291. WriteRawByte((byte)(value >> 32));
  292. WriteRawByte((byte)(value >> 40));
  293. WriteRawByte((byte)(value >> 48));
  294. WriteRawByte((byte)(value >> 56));
  295. }
  296. public void WriteRawByte(byte value) {
  297. if (position == limit) {
  298. RefreshBuffer();
  299. }
  300. buffer[position++] = value;
  301. }
  302. public void WriteRawByte(uint value) {
  303. WriteRawByte((byte)value);
  304. }
  305. /// <summary>
  306. /// Writes out an array of bytes.
  307. /// </summary>
  308. public void WriteRawBytes(byte[] value) {
  309. WriteRawBytes(value, 0, value.Length);
  310. }
  311. /// <summary>
  312. /// Writes out part of an array of bytes.
  313. /// </summary>
  314. public void WriteRawBytes(byte[] value, int offset, int length) {
  315. if (limit - position >= length) {
  316. Array.Copy(value, offset, buffer, position, length);
  317. // We have room in the current buffer.
  318. position += length;
  319. } else {
  320. // Write extends past current buffer. Fill the rest of this buffer and
  321. // flush.
  322. int bytesWritten = limit - position;
  323. Array.Copy(value, offset, buffer, position, bytesWritten);
  324. offset += bytesWritten;
  325. length -= bytesWritten;
  326. position = limit;
  327. RefreshBuffer();
  328. // Now deal with the rest.
  329. // Since we have an output stream, this is our buffer
  330. // and buffer offset == 0
  331. if (length <= limit) {
  332. // Fits in new buffer.
  333. Array.Copy(value, offset, buffer, 0, length);
  334. position = length;
  335. } else {
  336. // Write is very big. Let's do it all at once.
  337. output.Write(value, offset, length);
  338. }
  339. }
  340. }
  341. #endregion
  342. #region Size computations
  343. const int LittleEndian64Size = 8;
  344. const int LittleEndian32Size = 4;
  345. /// <summary>
  346. /// Compute the number of bytes that would be needed to encode a
  347. /// double field, including the tag.
  348. /// </summary>
  349. public static int ComputeDoubleSize(int fieldNumber, double value) {
  350. return ComputeTagSize(fieldNumber) + LittleEndian64Size;
  351. }
  352. /// <summary>
  353. /// Compute the number of bytes that would be needed to encode a
  354. /// float field, including the tag.
  355. /// </summary>
  356. public static int ComputeFloatSize(int fieldNumber, float value) {
  357. return ComputeTagSize(fieldNumber) + LittleEndian32Size;
  358. }
  359. /// <summary>
  360. /// Compute the number of bytes that would be needed to encode a
  361. /// uint64 field, including the tag.
  362. /// </summary>
  363. public static int ComputeUInt64Size(int fieldNumber, ulong value) {
  364. return ComputeTagSize(fieldNumber) + ComputeRawVarint64Size(value);
  365. }
  366. /// <summary>
  367. /// Compute the number of bytes that would be needed to encode an
  368. /// int64 field, including the tag.
  369. /// </summary>
  370. public static int ComputeInt64Size(int fieldNumber, long value) {
  371. return ComputeTagSize(fieldNumber) + ComputeRawVarint64Size((ulong)value);
  372. }
  373. /// <summary>
  374. /// Compute the number of bytes that would be needed to encode an
  375. /// int32 field, including the tag.
  376. /// </summary>
  377. public static int ComputeInt32Size(int fieldNumber, int value) {
  378. if (value >= 0) {
  379. return ComputeTagSize(fieldNumber) + ComputeRawVarint32Size((uint)value);
  380. } else {
  381. // Must sign-extend.
  382. return ComputeTagSize(fieldNumber) + 10;
  383. }
  384. }
  385. /// <summary>
  386. /// Compute the number of bytes that would be needed to encode a
  387. /// fixed64 field, including the tag.
  388. /// </summary>
  389. public static int ComputeFixed64Size(int fieldNumber, ulong value) {
  390. return ComputeTagSize(fieldNumber) + LittleEndian64Size;
  391. }
  392. /// <summary>
  393. /// Compute the number of bytes that would be needed to encode a
  394. /// fixed32 field, including the tag.
  395. /// </summary>
  396. public static int ComputeFixed32Size(int fieldNumber, uint value) {
  397. return ComputeTagSize(fieldNumber) + LittleEndian32Size;
  398. }
  399. /// <summary>
  400. /// Compute the number of bytes that would be needed to encode a
  401. /// bool field, including the tag.
  402. /// </summary>
  403. public static int ComputeBoolSize(int fieldNumber, bool value) {
  404. return ComputeTagSize(fieldNumber) + 1;
  405. }
  406. /// <summary>
  407. /// Compute the number of bytes that would be needed to encode a
  408. /// string field, including the tag.
  409. /// </summary>
  410. public static int ComputeStringSize(int fieldNumber, String value) {
  411. int byteArraySize = Encoding.UTF8.GetByteCount(value);
  412. return ComputeTagSize(fieldNumber) +
  413. ComputeRawVarint32Size((uint)byteArraySize) +
  414. byteArraySize;
  415. }
  416. /// <summary>
  417. /// Compute the number of bytes that would be needed to encode a
  418. /// group field, including the tag.
  419. /// </summary>
  420. public static int ComputeGroupSize(int fieldNumber, IMessage value) {
  421. return ComputeTagSize(fieldNumber) * 2 + value.SerializedSize;
  422. }
  423. /// <summary>
  424. /// Compute the number of bytes that would be needed to encode a
  425. /// group field represented by an UnknownFieldSet, including the tag.
  426. /// </summary>
  427. public static int ComputeUnknownGroupSize(int fieldNumber,
  428. UnknownFieldSet value) {
  429. return ComputeTagSize(fieldNumber) * 2 + value.SerializedSize;
  430. }
  431. /// <summary>
  432. /// Compute the number of bytes that would be needed to encode an
  433. /// embedded message field, including the tag.
  434. /// </summary>
  435. public static int ComputeMessageSize(int fieldNumber, IMessage value) {
  436. int size = value.SerializedSize;
  437. return ComputeTagSize(fieldNumber) + ComputeRawVarint32Size((uint)size) + size;
  438. }
  439. /// <summary>
  440. /// Compute the number of bytes that would be needed to encode a
  441. /// bytes field, including the tag.
  442. /// </summary>
  443. public static int ComputeBytesSize(int fieldNumber, ByteString value) {
  444. return ComputeTagSize(fieldNumber) +
  445. ComputeRawVarint32Size((uint)value.Length) +
  446. value.Length;
  447. }
  448. /// <summary>
  449. /// Compute the number of bytes that would be needed to encode a
  450. /// uint32 field, including the tag.
  451. /// </summary>
  452. public static int ComputeUInt32Size(int fieldNumber, uint value) {
  453. return ComputeTagSize(fieldNumber) + ComputeRawVarint32Size(value);
  454. }
  455. /// <summary>
  456. /// Compute the number of bytes that would be needed to encode a
  457. /// enum field, including the tag. The caller is responsible for
  458. /// converting the enum value to its numeric value.
  459. /// </summary>
  460. public static int ComputeEnumSize(int fieldNumber, int value) {
  461. return ComputeTagSize(fieldNumber) + ComputeRawVarint32Size((uint)value);
  462. }
  463. /// <summary>
  464. /// Compute the number of bytes that would be needed to encode an
  465. /// sfixed32 field, including the tag.
  466. /// </summary>
  467. public static int ComputeSFixed32Size(int fieldNumber, int value) {
  468. return ComputeTagSize(fieldNumber) + LittleEndian32Size;
  469. }
  470. /// <summary>
  471. /// Compute the number of bytes that would be needed to encode an
  472. /// sfixed64 field, including the tag.
  473. /// </summary>
  474. public static int ComputeSFixed64Size(int fieldNumber, long value) {
  475. return ComputeTagSize(fieldNumber) + LittleEndian64Size;
  476. }
  477. /// <summary>
  478. /// Compute the number of bytes that would be needed to encode an
  479. /// sint32 field, including the tag.
  480. /// </summary>
  481. public static int ComputeSInt32Size(int fieldNumber, int value) {
  482. return ComputeTagSize(fieldNumber) +
  483. ComputeRawVarint32Size(EncodeZigZag32(value));
  484. }
  485. /// <summary>
  486. /// Compute the number of bytes that would be needed to encode an
  487. /// sint64 field, including the tag.
  488. /// </summary>
  489. public static int ComputeSInt64Size(int fieldNumber, long value) {
  490. return ComputeTagSize(fieldNumber) +
  491. ComputeRawVarint64Size(EncodeZigZag64(value));
  492. }
  493. /*
  494. * Compute the number of bytes that would be needed to encode a
  495. * MessageSet extension to the stream. For historical reasons,
  496. * the wire format differs from normal fields.
  497. */
  498. /// <summary>
  499. /// Compute the number of bytes that would be needed to encode a
  500. /// MessageSet extension to the stream. For historical reasons,
  501. /// the wire format differs from normal fields.
  502. /// </summary>
  503. public static int ComputeMessageSetExtensionSize(int fieldNumber, IMessage value) {
  504. return ComputeTagSize(WireFormat.MessageSetField.Item) * 2 +
  505. ComputeUInt32Size(WireFormat.MessageSetField.TypeID, (uint) fieldNumber) +
  506. ComputeMessageSize(WireFormat.MessageSetField.Message, value);
  507. }
  508. /// <summary>
  509. /// Compute the number of bytes that would be needed to encode an
  510. /// unparsed MessageSet extension field to the stream. For
  511. /// historical reasons, the wire format differs from normal fields.
  512. /// </summary>
  513. public static int ComputeRawMessageSetExtensionSize(int fieldNumber, ByteString value) {
  514. return ComputeTagSize(WireFormat.MessageSetField.Item) * 2 +
  515. ComputeUInt32Size(WireFormat.MessageSetField.TypeID, (uint) fieldNumber) +
  516. ComputeBytesSize(WireFormat.MessageSetField.Message, value);
  517. }
  518. /// <summary>
  519. /// Compute the number of bytes that would be needed to encode a varint.
  520. /// </summary>
  521. public static int ComputeRawVarint32Size(uint value) {
  522. if ((value & (0xffffffff << 7)) == 0) return 1;
  523. if ((value & (0xffffffff << 14)) == 0) return 2;
  524. if ((value & (0xffffffff << 21)) == 0) return 3;
  525. if ((value & (0xffffffff << 28)) == 0) return 4;
  526. return 5;
  527. }
  528. /// <summary>
  529. /// Compute the number of bytes that would be needed to encode a varint.
  530. /// </summary>
  531. public static int ComputeRawVarint64Size(ulong value) {
  532. if ((value & (0xffffffffffffffffL << 7)) == 0) return 1;
  533. if ((value & (0xffffffffffffffffL << 14)) == 0) return 2;
  534. if ((value & (0xffffffffffffffffL << 21)) == 0) return 3;
  535. if ((value & (0xffffffffffffffffL << 28)) == 0) return 4;
  536. if ((value & (0xffffffffffffffffL << 35)) == 0) return 5;
  537. if ((value & (0xffffffffffffffffL << 42)) == 0) return 6;
  538. if ((value & (0xffffffffffffffffL << 49)) == 0) return 7;
  539. if ((value & (0xffffffffffffffffL << 56)) == 0) return 8;
  540. if ((value & (0xffffffffffffffffL << 63)) == 0) return 9;
  541. return 10;
  542. }
  543. /*
  544. * Compute the number of bytes that would be needed to encode a
  545. * field of arbitrary type, including tag, to the stream.
  546. *
  547. * @param type The field's type.
  548. * @param number The field's number.
  549. * @param value Object representing the field's value. Must be of the exact
  550. * type which would be returned by
  551. * {@link Message#getField(FieldDescriptor)} for
  552. * this field.
  553. */
  554. public static int ComputeFieldSize(FieldType fieldType, int fieldNumber, Object value) {
  555. switch (fieldType) {
  556. case FieldType.Double: return ComputeDoubleSize(fieldNumber, (double)value);
  557. case FieldType.Float: return ComputeFloatSize(fieldNumber, (float)value);
  558. case FieldType.Int64: return ComputeInt64Size(fieldNumber, (long)value);
  559. case FieldType.UInt64: return ComputeUInt64Size(fieldNumber, (ulong)value);
  560. case FieldType.Int32: return ComputeInt32Size(fieldNumber, (int)value);
  561. case FieldType.Fixed64: return ComputeFixed64Size(fieldNumber, (ulong)value);
  562. case FieldType.Fixed32: return ComputeFixed32Size(fieldNumber, (uint)value);
  563. case FieldType.Bool: return ComputeBoolSize(fieldNumber, (bool)value);
  564. case FieldType.String: return ComputeStringSize(fieldNumber, (string)value);
  565. case FieldType.Group: return ComputeGroupSize(fieldNumber, (IMessage)value);
  566. case FieldType.Message: return ComputeMessageSize(fieldNumber, (IMessage)value);
  567. case FieldType.Bytes: return ComputeBytesSize(fieldNumber, (ByteString)value);
  568. case FieldType.UInt32: return ComputeUInt32Size(fieldNumber, (uint)value);
  569. case FieldType.SFixed32: return ComputeSFixed32Size(fieldNumber, (int)value);
  570. case FieldType.SFixed64: return ComputeSFixed64Size(fieldNumber, (long)value);
  571. case FieldType.SInt32: return ComputeSInt32Size(fieldNumber, (int)value);
  572. case FieldType.SInt64: return ComputeSInt64Size(fieldNumber, (long)value);
  573. case FieldType.Enum: return ComputeEnumSize(fieldNumber, ((EnumValueDescriptor)value).Number);
  574. default:
  575. throw new ArgumentOutOfRangeException("Invalid field type " + fieldType);
  576. }
  577. }
  578. /// <summary>
  579. /// Compute the number of bytes that would be needed to encode a tag.
  580. /// </summary>
  581. public static int ComputeTagSize(int fieldNumber) {
  582. return ComputeRawVarint32Size(WireFormat.MakeTag(fieldNumber, 0));
  583. }
  584. #endregion
  585. /// <summary>
  586. /// Encode a 32-bit value with ZigZag encoding.
  587. /// </summary>
  588. /// <remarks>
  589. /// ZigZag encodes signed integers into values that can be efficiently
  590. /// encoded with varint. (Otherwise, negative values must be
  591. /// sign-extended to 64 bits to be varint encoded, thus always taking
  592. /// 10 bytes on the wire.)
  593. /// </remarks>
  594. public static uint EncodeZigZag32(int n) {
  595. // Note: the right-shift must be arithmetic
  596. return (uint)((n << 1) ^ (n >> 31));
  597. }
  598. /// <summary>
  599. /// Encode a 64-bit value with ZigZag encoding.
  600. /// </summary>
  601. /// <remarks>
  602. /// ZigZag encodes signed integers into values that can be efficiently
  603. /// encoded with varint. (Otherwise, negative values must be
  604. /// sign-extended to 64 bits to be varint encoded, thus always taking
  605. /// 10 bytes on the wire.)
  606. /// </remarks>
  607. public static ulong EncodeZigZag64(long n) {
  608. return (ulong)((n << 1) ^ (n >> 63));
  609. }
  610. private void RefreshBuffer() {
  611. if (output == null) {
  612. // We're writing to a single buffer.
  613. throw new OutOfSpaceException();
  614. }
  615. // Since we have an output stream, this is our buffer
  616. // and buffer offset == 0
  617. output.Write(buffer, 0, position);
  618. position = 0;
  619. }
  620. /// <summary>
  621. /// Indicates that a CodedOutputStream wrapping a flat byte array
  622. /// ran out of space.
  623. /// </summary>
  624. public class OutOfSpaceException : IOException {
  625. internal OutOfSpaceException()
  626. : base("CodedOutputStream was writing to a flat byte array and ran out of space.") {
  627. }
  628. }
  629. public void Flush() {
  630. if (output != null) {
  631. RefreshBuffer();
  632. }
  633. }
  634. /// <summary>
  635. /// Verifies that SpaceLeft returns zero. It's common to create a byte array
  636. /// that is exactly big enough to hold a message, then write to it with
  637. /// a CodedOutputStream. Calling CheckNoSpaceLeft after writing verifies that
  638. /// the message was actually as big as expected, which can help bugs.
  639. /// </summary>
  640. public void CheckNoSpaceLeft() {
  641. if (SpaceLeft != 0) {
  642. throw new InvalidOperationException("Did not write as much data as expected.");
  643. }
  644. }
  645. /// <summary>
  646. /// If writing to a flat array, returns the space left in the array. Otherwise,
  647. /// throws an InvalidOperationException.
  648. /// </summary>
  649. public int SpaceLeft {
  650. get {
  651. if (output == null) {
  652. return limit - position;
  653. } else {
  654. throw new InvalidOperationException(
  655. "SpaceLeft can only be called on CodedOutputStreams that are " +
  656. "writing to a flat array.");
  657. }
  658. }
  659. }
  660. }
  661. }