CodedOutputStream.cs 27 KB

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