CodedOutputStream.cs 28 KB

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