blob: a11f2420e31335c9155de57c4e156a72e5f0dec5 [file] [log] [blame]
Brian Silverman9c614bc2016-02-15 20:20:02 -05001#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
Austin Schuh40c16522018-10-28 20:27:54 -070033using Google.Protobuf.Collections;
Brian Silverman9c614bc2016-02-15 20:20:02 -050034using Google.Protobuf.Compatibility;
35using Google.Protobuf.WellKnownTypes;
36using System;
37using System.Collections.Generic;
38
39namespace Google.Protobuf
40{
41 /// <summary>
42 /// Factory methods for <see cref="FieldCodec{T}"/>.
43 /// </summary>
44 public static class FieldCodec
45 {
46 // TODO: Avoid the "dual hit" of lambda expressions: create open delegates instead. (At least test...)
47
48 /// <summary>
49 /// Retrieves a codec suitable for a string field with the given tag.
50 /// </summary>
51 /// <param name="tag">The tag.</param>
52 /// <returns>A codec for the given tag.</returns>
53 public static FieldCodec<string> ForString(uint tag)
54 {
55 return new FieldCodec<string>(input => input.ReadString(), (output, value) => output.WriteString(value), CodedOutputStream.ComputeStringSize, tag);
56 }
57
58 /// <summary>
59 /// Retrieves a codec suitable for a bytes field with the given tag.
60 /// </summary>
61 /// <param name="tag">The tag.</param>
62 /// <returns>A codec for the given tag.</returns>
63 public static FieldCodec<ByteString> ForBytes(uint tag)
64 {
65 return new FieldCodec<ByteString>(input => input.ReadBytes(), (output, value) => output.WriteBytes(value), CodedOutputStream.ComputeBytesSize, tag);
66 }
67
68 /// <summary>
69 /// Retrieves a codec suitable for a bool field with the given tag.
70 /// </summary>
71 /// <param name="tag">The tag.</param>
72 /// <returns>A codec for the given tag.</returns>
73 public static FieldCodec<bool> ForBool(uint tag)
74 {
75 return new FieldCodec<bool>(input => input.ReadBool(), (output, value) => output.WriteBool(value), CodedOutputStream.ComputeBoolSize, tag);
76 }
77
78 /// <summary>
79 /// Retrieves a codec suitable for an int32 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> ForInt32(uint tag)
84 {
85 return new FieldCodec<int>(input => input.ReadInt32(), (output, value) => output.WriteInt32(value), CodedOutputStream.ComputeInt32Size, tag);
86 }
87
88 /// <summary>
89 /// Retrieves a codec suitable for an sint32 field with the given tag.
90 /// </summary>
91 /// <param name="tag">The tag.</param>
92 /// <returns>A codec for the given tag.</returns>
93 public static FieldCodec<int> ForSInt32(uint tag)
94 {
95 return new FieldCodec<int>(input => input.ReadSInt32(), (output, value) => output.WriteSInt32(value), CodedOutputStream.ComputeSInt32Size, tag);
96 }
97
98 /// <summary>
99 /// Retrieves a codec suitable for a fixed32 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<uint> ForFixed32(uint tag)
104 {
105 return new FieldCodec<uint>(input => input.ReadFixed32(), (output, value) => output.WriteFixed32(value), 4, tag);
106 }
107
108 /// <summary>
109 /// Retrieves a codec suitable for an sfixed32 field with the given tag.
110 /// </summary>
111 /// <param name="tag">The tag.</param>
112 /// <returns>A codec for the given tag.</returns>
113 public static FieldCodec<int> ForSFixed32(uint tag)
114 {
115 return new FieldCodec<int>(input => input.ReadSFixed32(), (output, value) => output.WriteSFixed32(value), 4, tag);
116 }
117
118 /// <summary>
119 /// Retrieves a codec suitable for a uint32 field with the given tag.
120 /// </summary>
121 /// <param name="tag">The tag.</param>
122 /// <returns>A codec for the given tag.</returns>
123 public static FieldCodec<uint> ForUInt32(uint tag)
124 {
125 return new FieldCodec<uint>(input => input.ReadUInt32(), (output, value) => output.WriteUInt32(value), CodedOutputStream.ComputeUInt32Size, tag);
126 }
127
128 /// <summary>
129 /// Retrieves a codec suitable for an int64 field with the given tag.
130 /// </summary>
131 /// <param name="tag">The tag.</param>
132 /// <returns>A codec for the given tag.</returns>
133 public static FieldCodec<long> ForInt64(uint tag)
134 {
135 return new FieldCodec<long>(input => input.ReadInt64(), (output, value) => output.WriteInt64(value), CodedOutputStream.ComputeInt64Size, tag);
136 }
137
138 /// <summary>
139 /// Retrieves a codec suitable for an sint64 field with the given tag.
140 /// </summary>
141 /// <param name="tag">The tag.</param>
142 /// <returns>A codec for the given tag.</returns>
143 public static FieldCodec<long> ForSInt64(uint tag)
144 {
145 return new FieldCodec<long>(input => input.ReadSInt64(), (output, value) => output.WriteSInt64(value), CodedOutputStream.ComputeSInt64Size, tag);
146 }
147
148 /// <summary>
149 /// Retrieves a codec suitable for a fixed64 field with the given tag.
150 /// </summary>
151 /// <param name="tag">The tag.</param>
152 /// <returns>A codec for the given tag.</returns>
153 public static FieldCodec<ulong> ForFixed64(uint tag)
154 {
155 return new FieldCodec<ulong>(input => input.ReadFixed64(), (output, value) => output.WriteFixed64(value), 8, tag);
156 }
157
158 /// <summary>
159 /// Retrieves a codec suitable for an sfixed64 field with the given tag.
160 /// </summary>
161 /// <param name="tag">The tag.</param>
162 /// <returns>A codec for the given tag.</returns>
163 public static FieldCodec<long> ForSFixed64(uint tag)
164 {
165 return new FieldCodec<long>(input => input.ReadSFixed64(), (output, value) => output.WriteSFixed64(value), 8, tag);
166 }
167
168 /// <summary>
169 /// Retrieves a codec suitable for a uint64 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<ulong> ForUInt64(uint tag)
174 {
175 return new FieldCodec<ulong>(input => input.ReadUInt64(), (output, value) => output.WriteUInt64(value), CodedOutputStream.ComputeUInt64Size, tag);
176 }
177
178 /// <summary>
179 /// Retrieves a codec suitable for a float field with the given tag.
180 /// </summary>
181 /// <param name="tag">The tag.</param>
182 /// <returns>A codec for the given tag.</returns>
183 public static FieldCodec<float> ForFloat(uint tag)
184 {
185 return new FieldCodec<float>(input => input.ReadFloat(), (output, value) => output.WriteFloat(value), CodedOutputStream.ComputeFloatSize, tag);
186 }
187
188 /// <summary>
189 /// Retrieves a codec suitable for a double field with the given tag.
190 /// </summary>
191 /// <param name="tag">The tag.</param>
192 /// <returns>A codec for the given tag.</returns>
193 public static FieldCodec<double> ForDouble(uint tag)
194 {
195 return new FieldCodec<double>(input => input.ReadDouble(), (output, value) => output.WriteDouble(value), CodedOutputStream.ComputeDoubleSize, tag);
196 }
197
198 // Enums are tricky. We can probably use expression trees to build these delegates automatically,
199 // but it's easy to generate the code for it.
200
201 /// <summary>
202 /// Retrieves a codec suitable for an enum field with the given tag.
203 /// </summary>
204 /// <param name="tag">The tag.</param>
205 /// <param name="toInt32">A conversion function from <see cref="Int32"/> to the enum type.</param>
206 /// <param name="fromInt32">A conversion function from the enum type to <see cref="Int32"/>.</param>
207 /// <returns>A codec for the given tag.</returns>
208 public static FieldCodec<T> ForEnum<T>(uint tag, Func<T, int> toInt32, Func<int, T> fromInt32)
209 {
210 return new FieldCodec<T>(input => fromInt32(
211 input.ReadEnum()),
212 (output, value) => output.WriteEnum(toInt32(value)),
213 value => CodedOutputStream.ComputeEnumSize(toInt32(value)), tag);
214 }
215
216 /// <summary>
217 /// Retrieves a codec suitable for a message field with the given tag.
218 /// </summary>
219 /// <param name="tag">The tag.</param>
220 /// <param name="parser">A parser to use for the message type.</param>
221 /// <returns>A codec for the given tag.</returns>
222 public static FieldCodec<T> ForMessage<T>(uint tag, MessageParser<T> parser) where T : IMessage<T>
223 {
224 return new FieldCodec<T>(input => { T message = parser.CreateTemplate(); input.ReadMessage(message); return message; },
225 (output, value) => output.WriteMessage(value), message => CodedOutputStream.ComputeMessageSize(message), tag);
226 }
227
228 /// <summary>
229 /// Creates a codec for a wrapper type of a class - which must be string or ByteString.
230 /// </summary>
231 public static FieldCodec<T> ForClassWrapper<T>(uint tag) where T : class
232 {
233 var nestedCodec = WrapperCodecs.GetCodec<T>();
234 return new FieldCodec<T>(
235 input => WrapperCodecs.Read<T>(input, nestedCodec),
236 (output, value) => WrapperCodecs.Write<T>(output, value, nestedCodec),
237 value => WrapperCodecs.CalculateSize<T>(value, nestedCodec),
238 tag,
239 null); // Default value for the wrapper
240 }
241
242 /// <summary>
243 /// Creates a codec for a wrapper type of a struct - which must be Int32, Int64, UInt32, UInt64,
244 /// Bool, Single or Double.
245 /// </summary>
246 public static FieldCodec<T?> ForStructWrapper<T>(uint tag) where T : struct
247 {
248 var nestedCodec = WrapperCodecs.GetCodec<T>();
249 return new FieldCodec<T?>(
250 input => WrapperCodecs.Read<T>(input, nestedCodec),
251 (output, value) => WrapperCodecs.Write<T>(output, value.Value, nestedCodec),
252 value => value == null ? 0 : WrapperCodecs.CalculateSize<T>(value.Value, nestedCodec),
253 tag,
254 null); // Default value for the wrapper
255 }
256
257 /// <summary>
258 /// Helper code to create codecs for wrapper types.
259 /// </summary>
260 /// <remarks>
261 /// Somewhat ugly with all the static methods, but the conversions involved to/from nullable types make it
262 /// slightly tricky to improve. So long as we keep the public API (ForClassWrapper, ForStructWrapper) in place,
263 /// we can refactor later if we come up with something cleaner.
264 /// </remarks>
265 private static class WrapperCodecs
266 {
267 private static readonly Dictionary<System.Type, object> Codecs = new Dictionary<System.Type, object>
268 {
269 { typeof(bool), ForBool(WireFormat.MakeTag(WrappersReflection.WrapperValueFieldNumber, WireFormat.WireType.Varint)) },
270 { typeof(int), ForInt32(WireFormat.MakeTag(WrappersReflection.WrapperValueFieldNumber, WireFormat.WireType.Varint)) },
271 { typeof(long), ForInt64(WireFormat.MakeTag(WrappersReflection.WrapperValueFieldNumber, WireFormat.WireType.Varint)) },
272 { typeof(uint), ForUInt32(WireFormat.MakeTag(WrappersReflection.WrapperValueFieldNumber, WireFormat.WireType.Varint)) },
273 { typeof(ulong), ForUInt64(WireFormat.MakeTag(WrappersReflection.WrapperValueFieldNumber, WireFormat.WireType.Varint)) },
274 { typeof(float), ForFloat(WireFormat.MakeTag(WrappersReflection.WrapperValueFieldNumber, WireFormat.WireType.Fixed32)) },
275 { typeof(double), ForDouble(WireFormat.MakeTag(WrappersReflection.WrapperValueFieldNumber, WireFormat.WireType.Fixed64)) },
276 { typeof(string), ForString(WireFormat.MakeTag(WrappersReflection.WrapperValueFieldNumber, WireFormat.WireType.LengthDelimited)) },
277 { typeof(ByteString), ForBytes(WireFormat.MakeTag(WrappersReflection.WrapperValueFieldNumber, WireFormat.WireType.LengthDelimited)) }
278 };
279
280 /// <summary>
281 /// Returns a field codec which effectively wraps a value of type T in a message.
282 ///
283 /// </summary>
284 internal static FieldCodec<T> GetCodec<T>()
285 {
286 object value;
287 if (!Codecs.TryGetValue(typeof(T), out value))
288 {
289 throw new InvalidOperationException("Invalid type argument requested for wrapper codec: " + typeof(T));
290 }
291 return (FieldCodec<T>) value;
292 }
293
294 internal static T Read<T>(CodedInputStream input, FieldCodec<T> codec)
295 {
296 int length = input.ReadLength();
297 int oldLimit = input.PushLimit(length);
298
299 uint tag;
300 T value = codec.DefaultValue;
301 while ((tag = input.ReadTag()) != 0)
302 {
303 if (tag == codec.Tag)
304 {
305 value = codec.Read(input);
306 }
307 else
308 {
309 input.SkipLastField();
310 }
311
312 }
313 input.CheckReadEndOfStreamTag();
314 input.PopLimit(oldLimit);
315
316 return value;
317 }
318
319 internal static void Write<T>(CodedOutputStream output, T value, FieldCodec<T> codec)
320 {
321 output.WriteLength(codec.CalculateSizeWithTag(value));
322 codec.WriteTagAndValue(output, value);
323 }
324
325 internal static int CalculateSize<T>(T value, FieldCodec<T> codec)
326 {
327 int fieldLength = codec.CalculateSizeWithTag(value);
328 return CodedOutputStream.ComputeLengthSize(fieldLength) + fieldLength;
329 }
330 }
331 }
332
333 /// <summary>
334 /// <para>
335 /// An encode/decode pair for a single field. This effectively encapsulates
336 /// all the information needed to read or write the field value from/to a coded
337 /// stream.
338 /// </para>
339 /// <para>
340 /// This class is public and has to be as it is used by generated code, but its public
341 /// API is very limited - just what the generated code needs to call directly.
342 /// </para>
343 /// </summary>
344 /// <remarks>
345 /// This never writes default values to the stream, and does not address "packedness"
346 /// in repeated fields itself, other than to know whether or not the field *should* be packed.
347 /// </remarks>
348 public sealed class FieldCodec<T>
349 {
Austin Schuh40c16522018-10-28 20:27:54 -0700350 private static readonly EqualityComparer<T> EqualityComparer = ProtobufEqualityComparers.GetEqualityComparer<T>();
Brian Silverman9c614bc2016-02-15 20:20:02 -0500351 private static readonly T DefaultDefault;
Austin Schuh40c16522018-10-28 20:27:54 -0700352 // Only non-nullable value types support packing. This is the simplest way of detecting that.
353 private static readonly bool TypeSupportsPacking = default(T) != null;
Brian Silverman9c614bc2016-02-15 20:20:02 -0500354
355 static FieldCodec()
356 {
357 if (typeof(T) == typeof(string))
358 {
359 DefaultDefault = (T)(object)"";
360 }
361 else if (typeof(T) == typeof(ByteString))
362 {
363 DefaultDefault = (T)(object)ByteString.Empty;
364 }
365 // Otherwise it's the default value of the CLR type
366 }
367
368 internal static bool IsPackedRepeatedField(uint tag) =>
369 TypeSupportsPacking && WireFormat.GetTagWireType(tag) == WireFormat.WireType.LengthDelimited;
370
371 internal bool PackedRepeatedField { get; }
372
373 /// <summary>
374 /// Returns a delegate to write a value (unconditionally) to a coded output stream.
375 /// </summary>
376 internal Action<CodedOutputStream, T> ValueWriter { get; }
377
378 /// <summary>
379 /// Returns the size calculator for just a value.
380 /// </summary>
381 internal Func<T, int> ValueSizeCalculator { get; }
382
383 /// <summary>
384 /// Returns a delegate to read a value from a coded input stream. It is assumed that
385 /// the stream is already positioned on the appropriate tag.
386 /// </summary>
387 internal Func<CodedInputStream, T> ValueReader { get; }
388
389 /// <summary>
390 /// Returns the fixed size for an entry, or 0 if sizes vary.
391 /// </summary>
392 internal int FixedSize { get; }
393
394 /// <summary>
395 /// Gets the tag of the codec.
396 /// </summary>
397 /// <value>
398 /// The tag of the codec.
399 /// </value>
400 internal uint Tag { get; }
401
402 /// <summary>
403 /// Default value for this codec. Usually the same for every instance of the same type, but
404 /// for string/ByteString wrapper fields the codec's default value is null, whereas for
405 /// other string/ByteString fields it's "" or ByteString.Empty.
406 /// </summary>
407 /// <value>
408 /// The default value of the codec's type.
409 /// </value>
410 internal T DefaultValue { get; }
411
412 private readonly int tagSize;
413
414 internal FieldCodec(
415 Func<CodedInputStream, T> reader,
416 Action<CodedOutputStream, T> writer,
417 int fixedSize,
418 uint tag) : this(reader, writer, _ => fixedSize, tag)
419 {
420 FixedSize = fixedSize;
421 }
422
423 internal FieldCodec(
424 Func<CodedInputStream, T> reader,
425 Action<CodedOutputStream, T> writer,
426 Func<T, int> sizeCalculator,
427 uint tag) : this(reader, writer, sizeCalculator, tag, DefaultDefault)
428 {
429 }
430
431 internal FieldCodec(
432 Func<CodedInputStream, T> reader,
433 Action<CodedOutputStream, T> writer,
434 Func<T, int> sizeCalculator,
435 uint tag,
436 T defaultValue)
437 {
438 ValueReader = reader;
439 ValueWriter = writer;
440 ValueSizeCalculator = sizeCalculator;
441 FixedSize = 0;
442 Tag = tag;
443 DefaultValue = defaultValue;
444 tagSize = CodedOutputStream.ComputeRawVarint32Size(tag);
445 // Detect packed-ness once, so we can check for it within RepeatedField<T>.
446 PackedRepeatedField = IsPackedRepeatedField(tag);
447 }
448
449 /// <summary>
450 /// Write a tag and the given value, *if* the value is not the default.
451 /// </summary>
452 public void WriteTagAndValue(CodedOutputStream output, T value)
453 {
454 if (!IsDefault(value))
455 {
456 output.WriteTag(Tag);
457 ValueWriter(output, value);
458 }
459 }
460
461 /// <summary>
462 /// Reads a value of the codec type from the given <see cref="CodedInputStream"/>.
463 /// </summary>
464 /// <param name="input">The input stream to read from.</param>
465 /// <returns>The value read from the stream.</returns>
466 public T Read(CodedInputStream input) => ValueReader(input);
467
468 /// <summary>
469 /// Calculates the size required to write the given value, with a tag,
470 /// if the value is not the default.
471 /// </summary>
472 public int CalculateSizeWithTag(T value) => IsDefault(value) ? 0 : ValueSizeCalculator(value) + tagSize;
473
Austin Schuh40c16522018-10-28 20:27:54 -0700474 private bool IsDefault(T value) => EqualityComparer.Equals(value, DefaultValue);
Brian Silverman9c614bc2016-02-15 20:20:02 -0500475 }
476}