FieldCodec.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474
  1. #region Copyright notice and license
  2. // Protocol Buffers - Google's data interchange format
  3. // Copyright 2015 Google Inc. All rights reserved.
  4. // https://developers.google.com/protocol-buffers/
  5. //
  6. // Redistribution and use in source and binary forms, with or without
  7. // modification, are permitted provided that the following conditions are
  8. // met:
  9. //
  10. // * Redistributions of source code must retain the above copyright
  11. // notice, this list of conditions and the following disclaimer.
  12. // * Redistributions in binary form must reproduce the above
  13. // copyright notice, this list of conditions and the following disclaimer
  14. // in the documentation and/or other materials provided with the
  15. // distribution.
  16. // * Neither the name of Google Inc. nor the names of its
  17. // contributors may be used to endorse or promote products derived from
  18. // this software without specific prior written permission.
  19. //
  20. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  21. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  22. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  23. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  24. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  25. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  26. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  27. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  28. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  29. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  30. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  31. #endregion
  32. using Google.Protobuf.Compatibility;
  33. using Google.Protobuf.WellKnownTypes;
  34. using System;
  35. using System.Collections.Generic;
  36. namespace Google.Protobuf
  37. {
  38. /// <summary>
  39. /// Factory methods for <see cref="FieldCodec{T}"/>.
  40. /// </summary>
  41. public static class FieldCodec
  42. {
  43. // TODO: Avoid the "dual hit" of lambda expressions: create open delegates instead. (At least test...)
  44. /// <summary>
  45. /// Retrieves a codec suitable for a string field with the given tag.
  46. /// </summary>
  47. /// <param name="tag">The tag.</param>
  48. /// <returns>A codec for the given tag.</returns>
  49. public static FieldCodec<string> ForString(uint tag)
  50. {
  51. return new FieldCodec<string>(input => input.ReadString(), (output, value) => output.WriteString(value), CodedOutputStream.ComputeStringSize, tag);
  52. }
  53. /// <summary>
  54. /// Retrieves a codec suitable for a bytes field with the given tag.
  55. /// </summary>
  56. /// <param name="tag">The tag.</param>
  57. /// <returns>A codec for the given tag.</returns>
  58. public static FieldCodec<ByteString> ForBytes(uint tag)
  59. {
  60. return new FieldCodec<ByteString>(input => input.ReadBytes(), (output, value) => output.WriteBytes(value), CodedOutputStream.ComputeBytesSize, tag);
  61. }
  62. /// <summary>
  63. /// Retrieves a codec suitable for a bool field with the given tag.
  64. /// </summary>
  65. /// <param name="tag">The tag.</param>
  66. /// <returns>A codec for the given tag.</returns>
  67. public static FieldCodec<bool> ForBool(uint tag)
  68. {
  69. return new FieldCodec<bool>(input => input.ReadBool(), (output, value) => output.WriteBool(value), CodedOutputStream.ComputeBoolSize, tag);
  70. }
  71. /// <summary>
  72. /// Retrieves a codec suitable for an int32 field with the given tag.
  73. /// </summary>
  74. /// <param name="tag">The tag.</param>
  75. /// <returns>A codec for the given tag.</returns>
  76. public static FieldCodec<int> ForInt32(uint tag)
  77. {
  78. return new FieldCodec<int>(input => input.ReadInt32(), (output, value) => output.WriteInt32(value), CodedOutputStream.ComputeInt32Size, tag);
  79. }
  80. /// <summary>
  81. /// Retrieves a codec suitable for an sint32 field with the given tag.
  82. /// </summary>
  83. /// <param name="tag">The tag.</param>
  84. /// <returns>A codec for the given tag.</returns>
  85. public static FieldCodec<int> ForSInt32(uint tag)
  86. {
  87. return new FieldCodec<int>(input => input.ReadSInt32(), (output, value) => output.WriteSInt32(value), CodedOutputStream.ComputeSInt32Size, tag);
  88. }
  89. /// <summary>
  90. /// Retrieves a codec suitable for a fixed32 field with the given tag.
  91. /// </summary>
  92. /// <param name="tag">The tag.</param>
  93. /// <returns>A codec for the given tag.</returns>
  94. public static FieldCodec<uint> ForFixed32(uint tag)
  95. {
  96. return new FieldCodec<uint>(input => input.ReadFixed32(), (output, value) => output.WriteFixed32(value), 4, tag);
  97. }
  98. /// <summary>
  99. /// Retrieves a codec suitable for an sfixed32 field with the given tag.
  100. /// </summary>
  101. /// <param name="tag">The tag.</param>
  102. /// <returns>A codec for the given tag.</returns>
  103. public static FieldCodec<int> ForSFixed32(uint tag)
  104. {
  105. return new FieldCodec<int>(input => input.ReadSFixed32(), (output, value) => output.WriteSFixed32(value), 4, tag);
  106. }
  107. /// <summary>
  108. /// Retrieves a codec suitable for a uint32 field with the given tag.
  109. /// </summary>
  110. /// <param name="tag">The tag.</param>
  111. /// <returns>A codec for the given tag.</returns>
  112. public static FieldCodec<uint> ForUInt32(uint tag)
  113. {
  114. return new FieldCodec<uint>(input => input.ReadUInt32(), (output, value) => output.WriteUInt32(value), CodedOutputStream.ComputeUInt32Size, tag);
  115. }
  116. /// <summary>
  117. /// Retrieves a codec suitable for an int64 field with the given tag.
  118. /// </summary>
  119. /// <param name="tag">The tag.</param>
  120. /// <returns>A codec for the given tag.</returns>
  121. public static FieldCodec<long> ForInt64(uint tag)
  122. {
  123. return new FieldCodec<long>(input => input.ReadInt64(), (output, value) => output.WriteInt64(value), CodedOutputStream.ComputeInt64Size, tag);
  124. }
  125. /// <summary>
  126. /// Retrieves a codec suitable for an sint64 field with the given tag.
  127. /// </summary>
  128. /// <param name="tag">The tag.</param>
  129. /// <returns>A codec for the given tag.</returns>
  130. public static FieldCodec<long> ForSInt64(uint tag)
  131. {
  132. return new FieldCodec<long>(input => input.ReadSInt64(), (output, value) => output.WriteSInt64(value), CodedOutputStream.ComputeSInt64Size, tag);
  133. }
  134. /// <summary>
  135. /// Retrieves a codec suitable for a fixed64 field with the given tag.
  136. /// </summary>
  137. /// <param name="tag">The tag.</param>
  138. /// <returns>A codec for the given tag.</returns>
  139. public static FieldCodec<ulong> ForFixed64(uint tag)
  140. {
  141. return new FieldCodec<ulong>(input => input.ReadFixed64(), (output, value) => output.WriteFixed64(value), 8, tag);
  142. }
  143. /// <summary>
  144. /// Retrieves a codec suitable for an sfixed64 field with the given tag.
  145. /// </summary>
  146. /// <param name="tag">The tag.</param>
  147. /// <returns>A codec for the given tag.</returns>
  148. public static FieldCodec<long> ForSFixed64(uint tag)
  149. {
  150. return new FieldCodec<long>(input => input.ReadSFixed64(), (output, value) => output.WriteSFixed64(value), 8, tag);
  151. }
  152. /// <summary>
  153. /// Retrieves a codec suitable for a uint64 field with the given tag.
  154. /// </summary>
  155. /// <param name="tag">The tag.</param>
  156. /// <returns>A codec for the given tag.</returns>
  157. public static FieldCodec<ulong> ForUInt64(uint tag)
  158. {
  159. return new FieldCodec<ulong>(input => input.ReadUInt64(), (output, value) => output.WriteUInt64(value), CodedOutputStream.ComputeUInt64Size, tag);
  160. }
  161. /// <summary>
  162. /// Retrieves a codec suitable for a float field with the given tag.
  163. /// </summary>
  164. /// <param name="tag">The tag.</param>
  165. /// <returns>A codec for the given tag.</returns>
  166. public static FieldCodec<float> ForFloat(uint tag)
  167. {
  168. return new FieldCodec<float>(input => input.ReadFloat(), (output, value) => output.WriteFloat(value), CodedOutputStream.ComputeFloatSize, tag);
  169. }
  170. /// <summary>
  171. /// Retrieves a codec suitable for a double field with the given tag.
  172. /// </summary>
  173. /// <param name="tag">The tag.</param>
  174. /// <returns>A codec for the given tag.</returns>
  175. public static FieldCodec<double> ForDouble(uint tag)
  176. {
  177. return new FieldCodec<double>(input => input.ReadDouble(), (output, value) => output.WriteDouble(value), CodedOutputStream.ComputeDoubleSize, tag);
  178. }
  179. // Enums are tricky. We can probably use expression trees to build these delegates automatically,
  180. // but it's easy to generate the code for it.
  181. /// <summary>
  182. /// Retrieves a codec suitable for an enum field with the given tag.
  183. /// </summary>
  184. /// <param name="tag">The tag.</param>
  185. /// <param name="toInt32">A conversion function from <see cref="Int32"/> to the enum type.</param>
  186. /// <param name="fromInt32">A conversion function from the enum type to <see cref="Int32"/>.</param>
  187. /// <returns>A codec for the given tag.</returns>
  188. public static FieldCodec<T> ForEnum<T>(uint tag, Func<T, int> toInt32, Func<int, T> fromInt32)
  189. {
  190. return new FieldCodec<T>(input => fromInt32(
  191. input.ReadEnum()),
  192. (output, value) => output.WriteEnum(toInt32(value)),
  193. value => CodedOutputStream.ComputeEnumSize(toInt32(value)), tag);
  194. }
  195. /// <summary>
  196. /// Retrieves a codec suitable for a message field with the given tag.
  197. /// </summary>
  198. /// <param name="tag">The tag.</param>
  199. /// <param name="parser">A parser to use for the message type.</param>
  200. /// <returns>A codec for the given tag.</returns>
  201. public static FieldCodec<T> ForMessage<T>(uint tag, MessageParser<T> parser) where T : IMessage<T>
  202. {
  203. return new FieldCodec<T>(input => { T message = parser.CreateTemplate(); input.ReadMessage(message); return message; },
  204. (output, value) => output.WriteMessage(value), message => CodedOutputStream.ComputeMessageSize(message), tag);
  205. }
  206. /// <summary>
  207. /// Creates a codec for a wrapper type of a class - which must be string or ByteString.
  208. /// </summary>
  209. public static FieldCodec<T> ForClassWrapper<T>(uint tag) where T : class
  210. {
  211. var nestedCodec = WrapperCodecs.GetCodec<T>();
  212. return new FieldCodec<T>(
  213. input => WrapperCodecs.Read<T>(input, nestedCodec),
  214. (output, value) => WrapperCodecs.Write<T>(output, value, nestedCodec),
  215. value => WrapperCodecs.CalculateSize<T>(value, nestedCodec),
  216. tag,
  217. null); // Default value for the wrapper
  218. }
  219. /// <summary>
  220. /// Creates a codec for a wrapper type of a struct - which must be Int32, Int64, UInt32, UInt64,
  221. /// Bool, Single or Double.
  222. /// </summary>
  223. public static FieldCodec<T?> ForStructWrapper<T>(uint tag) where T : struct
  224. {
  225. var nestedCodec = WrapperCodecs.GetCodec<T>();
  226. return new FieldCodec<T?>(
  227. input => WrapperCodecs.Read<T>(input, nestedCodec),
  228. (output, value) => WrapperCodecs.Write<T>(output, value.Value, nestedCodec),
  229. value => value == null ? 0 : WrapperCodecs.CalculateSize<T>(value.Value, nestedCodec),
  230. tag,
  231. null); // Default value for the wrapper
  232. }
  233. /// <summary>
  234. /// Helper code to create codecs for wrapper types.
  235. /// </summary>
  236. /// <remarks>
  237. /// Somewhat ugly with all the static methods, but the conversions involved to/from nullable types make it
  238. /// slightly tricky to improve. So long as we keep the public API (ForClassWrapper, ForStructWrapper) in place,
  239. /// we can refactor later if we come up with something cleaner.
  240. /// </remarks>
  241. private static class WrapperCodecs
  242. {
  243. private static readonly Dictionary<System.Type, object> Codecs = new Dictionary<System.Type, object>
  244. {
  245. { typeof(bool), ForBool(WireFormat.MakeTag(WrappersReflection.WrapperValueFieldNumber, WireFormat.WireType.Varint)) },
  246. { typeof(int), ForInt32(WireFormat.MakeTag(WrappersReflection.WrapperValueFieldNumber, WireFormat.WireType.Varint)) },
  247. { typeof(long), ForInt64(WireFormat.MakeTag(WrappersReflection.WrapperValueFieldNumber, WireFormat.WireType.Varint)) },
  248. { typeof(uint), ForUInt32(WireFormat.MakeTag(WrappersReflection.WrapperValueFieldNumber, WireFormat.WireType.Varint)) },
  249. { typeof(ulong), ForUInt64(WireFormat.MakeTag(WrappersReflection.WrapperValueFieldNumber, WireFormat.WireType.Varint)) },
  250. { typeof(float), ForFloat(WireFormat.MakeTag(WrappersReflection.WrapperValueFieldNumber, WireFormat.WireType.Fixed32)) },
  251. { typeof(double), ForDouble(WireFormat.MakeTag(WrappersReflection.WrapperValueFieldNumber, WireFormat.WireType.Fixed64)) },
  252. { typeof(string), ForString(WireFormat.MakeTag(WrappersReflection.WrapperValueFieldNumber, WireFormat.WireType.LengthDelimited)) },
  253. { typeof(ByteString), ForBytes(WireFormat.MakeTag(WrappersReflection.WrapperValueFieldNumber, WireFormat.WireType.LengthDelimited)) }
  254. };
  255. /// <summary>
  256. /// Returns a field codec which effectively wraps a value of type T in a message.
  257. ///
  258. /// </summary>
  259. internal static FieldCodec<T> GetCodec<T>()
  260. {
  261. object value;
  262. if (!Codecs.TryGetValue(typeof(T), out value))
  263. {
  264. throw new InvalidOperationException("Invalid type argument requested for wrapper codec: " + typeof(T));
  265. }
  266. return (FieldCodec<T>) value;
  267. }
  268. internal static T Read<T>(CodedInputStream input, FieldCodec<T> codec)
  269. {
  270. int length = input.ReadLength();
  271. int oldLimit = input.PushLimit(length);
  272. uint tag;
  273. T value = codec.DefaultValue;
  274. while ((tag = input.ReadTag()) != 0)
  275. {
  276. if (tag == codec.Tag)
  277. {
  278. value = codec.Read(input);
  279. }
  280. else
  281. {
  282. input.SkipLastField();
  283. }
  284. }
  285. input.CheckReadEndOfStreamTag();
  286. input.PopLimit(oldLimit);
  287. return value;
  288. }
  289. internal static void Write<T>(CodedOutputStream output, T value, FieldCodec<T> codec)
  290. {
  291. output.WriteLength(codec.CalculateSizeWithTag(value));
  292. codec.WriteTagAndValue(output, value);
  293. }
  294. internal static int CalculateSize<T>(T value, FieldCodec<T> codec)
  295. {
  296. int fieldLength = codec.CalculateSizeWithTag(value);
  297. return CodedOutputStream.ComputeLengthSize(fieldLength) + fieldLength;
  298. }
  299. }
  300. }
  301. /// <summary>
  302. /// <para>
  303. /// An encode/decode pair for a single field. This effectively encapsulates
  304. /// all the information needed to read or write the field value from/to a coded
  305. /// stream.
  306. /// </para>
  307. /// <para>
  308. /// This class is public and has to be as it is used by generated code, but its public
  309. /// API is very limited - just what the generated code needs to call directly.
  310. /// </para>
  311. /// </summary>
  312. /// <remarks>
  313. /// This never writes default values to the stream, and does not address "packedness"
  314. /// in repeated fields itself, other than to know whether or not the field *should* be packed.
  315. /// </remarks>
  316. public sealed class FieldCodec<T>
  317. {
  318. private static readonly T DefaultDefault;
  319. // Only non-nullable value types support packing. This is the simplest way of detecting that.
  320. private static readonly bool TypeSupportsPacking = default(T) != null;
  321. static FieldCodec()
  322. {
  323. if (typeof(T) == typeof(string))
  324. {
  325. DefaultDefault = (T)(object)"";
  326. }
  327. else if (typeof(T) == typeof(ByteString))
  328. {
  329. DefaultDefault = (T)(object)ByteString.Empty;
  330. }
  331. // Otherwise it's the default value of the CLR type
  332. }
  333. internal static bool IsPackedRepeatedField(uint tag) =>
  334. TypeSupportsPacking && WireFormat.GetTagWireType(tag) == WireFormat.WireType.LengthDelimited;
  335. internal bool PackedRepeatedField { get; }
  336. /// <summary>
  337. /// Returns a delegate to write a value (unconditionally) to a coded output stream.
  338. /// </summary>
  339. internal Action<CodedOutputStream, T> ValueWriter { get; }
  340. /// <summary>
  341. /// Returns the size calculator for just a value.
  342. /// </summary>
  343. internal Func<T, int> ValueSizeCalculator { get; }
  344. /// <summary>
  345. /// Returns a delegate to read a value from a coded input stream. It is assumed that
  346. /// the stream is already positioned on the appropriate tag.
  347. /// </summary>
  348. internal Func<CodedInputStream, T> ValueReader { get; }
  349. /// <summary>
  350. /// Returns the fixed size for an entry, or 0 if sizes vary.
  351. /// </summary>
  352. internal int FixedSize { get; }
  353. /// <summary>
  354. /// Gets the tag of the codec.
  355. /// </summary>
  356. /// <value>
  357. /// The tag of the codec.
  358. /// </value>
  359. internal uint Tag { get; }
  360. /// <summary>
  361. /// Default value for this codec. Usually the same for every instance of the same type, but
  362. /// for string/ByteString wrapper fields the codec's default value is null, whereas for
  363. /// other string/ByteString fields it's "" or ByteString.Empty.
  364. /// </summary>
  365. /// <value>
  366. /// The default value of the codec's type.
  367. /// </value>
  368. internal T DefaultValue { get; }
  369. private readonly int tagSize;
  370. internal FieldCodec(
  371. Func<CodedInputStream, T> reader,
  372. Action<CodedOutputStream, T> writer,
  373. int fixedSize,
  374. uint tag) : this(reader, writer, _ => fixedSize, tag)
  375. {
  376. FixedSize = fixedSize;
  377. }
  378. internal FieldCodec(
  379. Func<CodedInputStream, T> reader,
  380. Action<CodedOutputStream, T> writer,
  381. Func<T, int> sizeCalculator,
  382. uint tag) : this(reader, writer, sizeCalculator, tag, DefaultDefault)
  383. {
  384. }
  385. internal FieldCodec(
  386. Func<CodedInputStream, T> reader,
  387. Action<CodedOutputStream, T> writer,
  388. Func<T, int> sizeCalculator,
  389. uint tag,
  390. T defaultValue)
  391. {
  392. ValueReader = reader;
  393. ValueWriter = writer;
  394. ValueSizeCalculator = sizeCalculator;
  395. FixedSize = 0;
  396. Tag = tag;
  397. DefaultValue = defaultValue;
  398. tagSize = CodedOutputStream.ComputeRawVarint32Size(tag);
  399. // Detect packed-ness once, so we can check for it within RepeatedField<T>.
  400. PackedRepeatedField = IsPackedRepeatedField(tag);
  401. }
  402. /// <summary>
  403. /// Write a tag and the given value, *if* the value is not the default.
  404. /// </summary>
  405. public void WriteTagAndValue(CodedOutputStream output, T value)
  406. {
  407. if (!IsDefault(value))
  408. {
  409. output.WriteTag(Tag);
  410. ValueWriter(output, value);
  411. }
  412. }
  413. /// <summary>
  414. /// Reads a value of the codec type from the given <see cref="CodedInputStream"/>.
  415. /// </summary>
  416. /// <param name="input">The input stream to read from.</param>
  417. /// <returns>The value read from the stream.</returns>
  418. public T Read(CodedInputStream input) => ValueReader(input);
  419. /// <summary>
  420. /// Calculates the size required to write the given value, with a tag,
  421. /// if the value is not the default.
  422. /// </summary>
  423. public int CalculateSizeWithTag(T value) => IsDefault(value) ? 0 : ValueSizeCalculator(value) + tagSize;
  424. private bool IsDefault(T value) => EqualityComparer<T>.Default.Equals(value, DefaultValue);
  425. }
  426. }