FieldCodec.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379
  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 System;
  33. using System.Collections.Generic;
  34. namespace Google.Protobuf
  35. {
  36. /// <summary>
  37. /// Factory methods for <see cref="FieldCodec{T}"/>.
  38. /// </summary>
  39. public static class FieldCodec
  40. {
  41. // TODO: Avoid the "dual hit" of lambda expressions: create open delegates instead. (At least test...)
  42. /// <summary>
  43. /// Retrieves a codec suitable for a string field with the given tag.
  44. /// </summary>
  45. /// <param name="tag">The tag.</param>
  46. /// <returns>A codec for the given tag.</returns>
  47. public static FieldCodec<string> ForString(uint tag)
  48. {
  49. return new FieldCodec<string>(input => input.ReadString(), (output, value) => output.WriteString(value), CodedOutputStream.ComputeStringSize, tag);
  50. }
  51. /// <summary>
  52. /// Retrieves a codec suitable for a bytes field with the given tag.
  53. /// </summary>
  54. /// <param name="tag">The tag.</param>
  55. /// <returns>A codec for the given tag.</returns>
  56. public static FieldCodec<ByteString> ForBytes(uint tag)
  57. {
  58. return new FieldCodec<ByteString>(input => input.ReadBytes(), (output, value) => output.WriteBytes(value), CodedOutputStream.ComputeBytesSize, tag);
  59. }
  60. /// <summary>
  61. /// Retrieves a codec suitable for a bool field with the given tag.
  62. /// </summary>
  63. /// <param name="tag">The tag.</param>
  64. /// <returns>A codec for the given tag.</returns>
  65. public static FieldCodec<bool> ForBool(uint tag)
  66. {
  67. return new FieldCodec<bool>(input => input.ReadBool(), (output, value) => output.WriteBool(value), CodedOutputStream.ComputeBoolSize, tag);
  68. }
  69. /// <summary>
  70. /// Retrieves a codec suitable for an int32 field with the given tag.
  71. /// </summary>
  72. /// <param name="tag">The tag.</param>
  73. /// <returns>A codec for the given tag.</returns>
  74. public static FieldCodec<int> ForInt32(uint tag)
  75. {
  76. return new FieldCodec<int>(input => input.ReadInt32(), (output, value) => output.WriteInt32(value), CodedOutputStream.ComputeInt32Size, tag);
  77. }
  78. /// <summary>
  79. /// Retrieves a codec suitable for an sint32 field with the given tag.
  80. /// </summary>
  81. /// <param name="tag">The tag.</param>
  82. /// <returns>A codec for the given tag.</returns>
  83. public static FieldCodec<int> ForSInt32(uint tag)
  84. {
  85. return new FieldCodec<int>(input => input.ReadSInt32(), (output, value) => output.WriteSInt32(value), CodedOutputStream.ComputeSInt32Size, tag);
  86. }
  87. /// <summary>
  88. /// Retrieves a codec suitable for a fixed32 field with the given tag.
  89. /// </summary>
  90. /// <param name="tag">The tag.</param>
  91. /// <returns>A codec for the given tag.</returns>
  92. public static FieldCodec<uint> ForFixed32(uint tag)
  93. {
  94. return new FieldCodec<uint>(input => input.ReadFixed32(), (output, value) => output.WriteFixed32(value), 4, tag);
  95. }
  96. /// <summary>
  97. /// Retrieves a codec suitable for an sfixed32 field with the given tag.
  98. /// </summary>
  99. /// <param name="tag">The tag.</param>
  100. /// <returns>A codec for the given tag.</returns>
  101. public static FieldCodec<int> ForSFixed32(uint tag)
  102. {
  103. return new FieldCodec<int>(input => input.ReadSFixed32(), (output, value) => output.WriteSFixed32(value), 4, tag);
  104. }
  105. /// <summary>
  106. /// Retrieves a codec suitable for a uint32 field with the given tag.
  107. /// </summary>
  108. /// <param name="tag">The tag.</param>
  109. /// <returns>A codec for the given tag.</returns>
  110. public static FieldCodec<uint> ForUInt32(uint tag)
  111. {
  112. return new FieldCodec<uint>(input => input.ReadUInt32(), (output, value) => output.WriteUInt32(value), CodedOutputStream.ComputeUInt32Size, tag);
  113. }
  114. /// <summary>
  115. /// Retrieves a codec suitable for an int64 field with the given tag.
  116. /// </summary>
  117. /// <param name="tag">The tag.</param>
  118. /// <returns>A codec for the given tag.</returns>
  119. public static FieldCodec<long> ForInt64(uint tag)
  120. {
  121. return new FieldCodec<long>(input => input.ReadInt64(), (output, value) => output.WriteInt64(value), CodedOutputStream.ComputeInt64Size, tag);
  122. }
  123. /// <summary>
  124. /// Retrieves a codec suitable for an sint64 field with the given tag.
  125. /// </summary>
  126. /// <param name="tag">The tag.</param>
  127. /// <returns>A codec for the given tag.</returns>
  128. public static FieldCodec<long> ForSInt64(uint tag)
  129. {
  130. return new FieldCodec<long>(input => input.ReadSInt64(), (output, value) => output.WriteSInt64(value), CodedOutputStream.ComputeSInt64Size, tag);
  131. }
  132. /// <summary>
  133. /// Retrieves a codec suitable for a fixed64 field with the given tag.
  134. /// </summary>
  135. /// <param name="tag">The tag.</param>
  136. /// <returns>A codec for the given tag.</returns>
  137. public static FieldCodec<ulong> ForFixed64(uint tag)
  138. {
  139. return new FieldCodec<ulong>(input => input.ReadFixed64(), (output, value) => output.WriteFixed64(value), 8, tag);
  140. }
  141. /// <summary>
  142. /// Retrieves a codec suitable for an sfixed64 field with the given tag.
  143. /// </summary>
  144. /// <param name="tag">The tag.</param>
  145. /// <returns>A codec for the given tag.</returns>
  146. public static FieldCodec<long> ForSFixed64(uint tag)
  147. {
  148. return new FieldCodec<long>(input => input.ReadSFixed64(), (output, value) => output.WriteSFixed64(value), 8, tag);
  149. }
  150. /// <summary>
  151. /// Retrieves a codec suitable for a uint64 field with the given tag.
  152. /// </summary>
  153. /// <param name="tag">The tag.</param>
  154. /// <returns>A codec for the given tag.</returns>
  155. public static FieldCodec<ulong> ForUInt64(uint tag)
  156. {
  157. return new FieldCodec<ulong>(input => input.ReadUInt64(), (output, value) => output.WriteUInt64(value), CodedOutputStream.ComputeUInt64Size, tag);
  158. }
  159. /// <summary>
  160. /// Retrieves a codec suitable for a float field with the given tag.
  161. /// </summary>
  162. /// <param name="tag">The tag.</param>
  163. /// <returns>A codec for the given tag.</returns>
  164. public static FieldCodec<float> ForFloat(uint tag)
  165. {
  166. return new FieldCodec<float>(input => input.ReadFloat(), (output, value) => output.WriteFloat(value), CodedOutputStream.ComputeFloatSize, tag);
  167. }
  168. /// <summary>
  169. /// Retrieves a codec suitable for a double field with the given tag.
  170. /// </summary>
  171. /// <param name="tag">The tag.</param>
  172. /// <returns>A codec for the given tag.</returns>
  173. public static FieldCodec<double> ForDouble(uint tag)
  174. {
  175. return new FieldCodec<double>(input => input.ReadDouble(), (output, value) => output.WriteDouble(value), CodedOutputStream.ComputeDoubleSize, tag);
  176. }
  177. // Enums are tricky. We can probably use expression trees to build these delegates automatically,
  178. // but it's easy to generate the code for it.
  179. /// <summary>
  180. /// Retrieves a codec suitable for an enum field with the given tag.
  181. /// </summary>
  182. /// <param name="tag">The tag.</param>
  183. /// <param name="toInt32">A conversion function from <see cref="Int32"/> to the enum type.</param>
  184. /// <param name="fromInt32">A conversion function from the enum type to <see cref="Int32"/>.</param>
  185. /// <returns>A codec for the given tag.</returns>
  186. public static FieldCodec<T> ForEnum<T>(uint tag, Func<T, int> toInt32, Func<int, T> fromInt32)
  187. {
  188. return new FieldCodec<T>(input => fromInt32(
  189. input.ReadEnum()),
  190. (output, value) => output.WriteEnum(toInt32(value)),
  191. value => CodedOutputStream.ComputeEnumSize(toInt32(value)), tag);
  192. }
  193. /// <summary>
  194. /// Retrieves a codec suitable for a message field with the given tag.
  195. /// </summary>
  196. /// <param name="tag">The tag.</param>
  197. /// <param name="parser">A parser to use for the message type.</param>
  198. /// <returns>A codec for the given tag.</returns>
  199. public static FieldCodec<T> ForMessage<T>(uint tag, MessageParser<T> parser) where T : IMessage
  200. {
  201. return new FieldCodec<T>(input => { T message = parser.CreateTemplate(); input.ReadMessage(message); return message; },
  202. (output, value) => output.WriteMessage(value), message => CodedOutputStream.ComputeMessageSize(message), tag);
  203. }
  204. }
  205. /// <summary>
  206. /// <para>
  207. /// An encode/decode pair for a single field. This effectively encapsulates
  208. /// all the information needed to read or write the field value from/to a coded
  209. /// stream.
  210. /// </para>
  211. /// <para>
  212. /// This class is public and has to be as it is used by generated code, but its public
  213. /// API is very limited - just what the generated code needs to call directly.
  214. /// </para>
  215. /// </summary>
  216. /// <remarks>
  217. /// This never writes default values to the stream, and does not address "packedness"
  218. /// in repeated fields itself, other than to know whether or not the field *should* be packed.
  219. /// </remarks>
  220. public sealed class FieldCodec<T>
  221. {
  222. private static readonly T DefaultDefault;
  223. // Only non-nullable value types support packing. This is the simplest way of detecting that.
  224. private static readonly bool TypeSupportsPacking = default(T) != null;
  225. static FieldCodec()
  226. {
  227. if (typeof(T) == typeof(string))
  228. {
  229. DefaultDefault = (T)(object)"";
  230. }
  231. else if (typeof(T) == typeof(ByteString))
  232. {
  233. DefaultDefault = (T)(object)ByteString.Empty;
  234. }
  235. // Otherwise it's the default value of the CLR type
  236. }
  237. internal static bool IsPackedRepeatedField(uint tag)
  238. {
  239. return TypeSupportsPacking && WireFormat.GetTagWireType(tag) == WireFormat.WireType.LengthDelimited;
  240. }
  241. internal readonly bool PackedRepeatedField;
  242. /// <summary>
  243. /// Returns a delegate to write a value (unconditionally) to a coded output stream.
  244. /// </summary>
  245. internal readonly Action<CodedOutputStream, T> ValueWriter;
  246. /// <summary>
  247. /// Returns the size calculator for just a value.
  248. /// </summary>
  249. internal readonly Func<T, int> ValueSizeCalculator;
  250. /// <summary>
  251. /// Returns a delegate to read a value from a coded input stream. It is assumed that
  252. /// the stream is already positioned on the appropriate tag.
  253. /// </summary>
  254. internal readonly Func<CodedInputStream, T> ValueReader;
  255. /// <summary>
  256. /// Returns the fixed size for an entry, or 0 if sizes vary.
  257. /// </summary>
  258. internal readonly int FixedSize;
  259. /// <summary>
  260. /// Gets the tag of the codec.
  261. /// </summary>
  262. /// <value>
  263. /// The tag of the codec.
  264. /// </value>
  265. internal readonly uint Tag;
  266. /// <summary>
  267. /// Default value for this codec. Usually the same for every instance of the same type, but
  268. /// for string/ByteString wrapper fields the codec's default value is null, whereas for
  269. /// other string/ByteString fields it's "" or ByteString.Empty.
  270. /// </summary>
  271. /// <value>
  272. /// The default value of the codec's type.
  273. /// </value>
  274. internal readonly T DefaultValue;
  275. private readonly int tagSize;
  276. internal FieldCodec(
  277. Func<CodedInputStream, T> reader,
  278. Action<CodedOutputStream, T> writer,
  279. int fixedSize,
  280. uint tag) : this(reader, writer, _ => fixedSize, tag)
  281. {
  282. FixedSize = fixedSize;
  283. }
  284. internal FieldCodec(
  285. Func<CodedInputStream, T> reader,
  286. Action<CodedOutputStream, T> writer,
  287. Func<T, int> sizeCalculator,
  288. uint tag) : this(reader, writer, sizeCalculator, tag, DefaultDefault)
  289. {
  290. }
  291. internal FieldCodec(
  292. Func<CodedInputStream, T> reader,
  293. Action<CodedOutputStream, T> writer,
  294. Func<T, int> sizeCalculator,
  295. uint tag,
  296. T defaultValue)
  297. {
  298. ValueReader = reader;
  299. ValueWriter = writer;
  300. ValueSizeCalculator = sizeCalculator;
  301. FixedSize = 0;
  302. Tag = tag;
  303. DefaultValue = defaultValue;
  304. tagSize = CodedOutputStream.ComputeRawVarint32Size(tag);
  305. // Detect packed-ness once, so we can check for it within RepeatedField<T>.
  306. PackedRepeatedField = IsPackedRepeatedField(tag);
  307. }
  308. /// <summary>
  309. /// Write a tag and the given value, *if* the value is not the default.
  310. /// </summary>
  311. public void WriteTagAndValue(CodedOutputStream output, T value)
  312. {
  313. if (!IsDefault(value))
  314. {
  315. output.WriteTag(Tag);
  316. ValueWriter(output, value);
  317. }
  318. }
  319. /// <summary>
  320. /// Reads a value of the codec type from the given <see cref="CodedInputStream"/>.
  321. /// </summary>
  322. /// <param name="input">The input stream to read from.</param>
  323. /// <returns>The value read from the stream.</returns>
  324. public T Read(CodedInputStream input)
  325. {
  326. return ValueReader(input);
  327. }
  328. /// <summary>
  329. /// Calculates the size required to write the given value, with a tag,
  330. /// if the value is not the default.
  331. /// </summary>
  332. public int CalculateSizeWithTag(T value)
  333. {
  334. return IsDefault(value) ? 0 : ValueSizeCalculator(value) + tagSize;
  335. }
  336. private bool IsDefault(T value)
  337. {
  338. return EqualityComparer<T>.Default.Equals(value, DefaultValue);
  339. }
  340. }
  341. }