#region Copyright notice and license
// Protocol Buffers - Google's data interchange format
// Copyright 2015 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#endregion
using LC.Google.Protobuf.Collections;
using LC.Google.Protobuf.Compatibility;
using LC.Google.Protobuf.WellKnownTypes;
using System;
using System.Collections.Generic;
using System.Security;
namespace LC.Google.Protobuf
{
///
/// Factory methods for .
///
public static class FieldCodec
{
// TODO: Avoid the "dual hit" of lambda expressions: create open delegates instead. (At least test...)
///
/// Retrieves a codec suitable for a string field with the given tag.
///
/// The tag.
/// A codec for the given tag.
public static FieldCodec ForString(uint tag)
{
return FieldCodec.ForString(tag, "");
}
///
/// Retrieves a codec suitable for a bytes field with the given tag.
///
/// The tag.
/// A codec for the given tag.
public static FieldCodec ForBytes(uint tag)
{
return FieldCodec.ForBytes(tag, ByteString.Empty);
}
///
/// Retrieves a codec suitable for a bool field with the given tag.
///
/// The tag.
/// A codec for the given tag.
public static FieldCodec ForBool(uint tag)
{
return FieldCodec.ForBool(tag, false);
}
///
/// Retrieves a codec suitable for an int32 field with the given tag.
///
/// The tag.
/// A codec for the given tag.
public static FieldCodec ForInt32(uint tag)
{
return FieldCodec.ForInt32(tag, 0);
}
///
/// Retrieves a codec suitable for an sint32 field with the given tag.
///
/// The tag.
/// A codec for the given tag.
public static FieldCodec ForSInt32(uint tag)
{
return FieldCodec.ForSInt32(tag, 0);
}
///
/// Retrieves a codec suitable for a fixed32 field with the given tag.
///
/// The tag.
/// A codec for the given tag.
public static FieldCodec ForFixed32(uint tag)
{
return FieldCodec.ForFixed32(tag, 0);
}
///
/// Retrieves a codec suitable for an sfixed32 field with the given tag.
///
/// The tag.
/// A codec for the given tag.
public static FieldCodec ForSFixed32(uint tag)
{
return FieldCodec.ForSFixed32(tag, 0);
}
///
/// Retrieves a codec suitable for a uint32 field with the given tag.
///
/// The tag.
/// A codec for the given tag.
public static FieldCodec ForUInt32(uint tag)
{
return FieldCodec.ForUInt32(tag, 0);
}
///
/// Retrieves a codec suitable for an int64 field with the given tag.
///
/// The tag.
/// A codec for the given tag.
public static FieldCodec ForInt64(uint tag)
{
return FieldCodec.ForInt64(tag, 0);
}
///
/// Retrieves a codec suitable for an sint64 field with the given tag.
///
/// The tag.
/// A codec for the given tag.
public static FieldCodec ForSInt64(uint tag)
{
return FieldCodec.ForSInt64(tag, 0);
}
///
/// Retrieves a codec suitable for a fixed64 field with the given tag.
///
/// The tag.
/// A codec for the given tag.
public static FieldCodec ForFixed64(uint tag)
{
return FieldCodec.ForFixed64(tag, 0);
}
///
/// Retrieves a codec suitable for an sfixed64 field with the given tag.
///
/// The tag.
/// A codec for the given tag.
public static FieldCodec ForSFixed64(uint tag)
{
return FieldCodec.ForSFixed64(tag, 0);
}
///
/// Retrieves a codec suitable for a uint64 field with the given tag.
///
/// The tag.
/// A codec for the given tag.
public static FieldCodec ForUInt64(uint tag)
{
return FieldCodec.ForUInt64(tag, 0);
}
///
/// Retrieves a codec suitable for a float field with the given tag.
///
/// The tag.
/// A codec for the given tag.
public static FieldCodec ForFloat(uint tag)
{
return FieldCodec.ForFloat(tag, 0);
}
///
/// Retrieves a codec suitable for a double field with the given tag.
///
/// The tag.
/// A codec for the given tag.
public static FieldCodec ForDouble(uint tag)
{
return FieldCodec.ForDouble(tag, 0);
}
// Enums are tricky. We can probably use expression trees to build these delegates automatically,
// but it's easy to generate the code for it.
///
/// Retrieves a codec suitable for an enum field with the given tag.
///
/// The tag.
/// A conversion function from to the enum type.
/// A conversion function from the enum type to .
/// A codec for the given tag.
public static FieldCodec ForEnum(uint tag, Func toInt32, Func fromInt32)
{
return FieldCodec.ForEnum(tag, toInt32, fromInt32, default(T));
}
///
/// Retrieves a codec suitable for a string field with the given tag.
///
/// The tag.
/// The default value.
/// A codec for the given tag.
public static FieldCodec ForString(uint tag, string defaultValue)
{
return new FieldCodec((ref ParseContext ctx) => ctx.ReadString(), (ref WriteContext ctx, string value) => ctx.WriteString(value), CodedOutputStream.ComputeStringSize, tag, defaultValue);
}
///
/// Retrieves a codec suitable for a bytes field with the given tag.
///
/// The tag.
/// The default value.
/// A codec for the given tag.
public static FieldCodec ForBytes(uint tag, ByteString defaultValue)
{
return new FieldCodec((ref ParseContext ctx) => ctx.ReadBytes(), (ref WriteContext ctx, ByteString value) => ctx.WriteBytes(value), CodedOutputStream.ComputeBytesSize, tag, defaultValue);
}
///
/// Retrieves a codec suitable for a bool field with the given tag.
///
/// The tag.
/// The default value.
/// A codec for the given tag.
public static FieldCodec ForBool(uint tag, bool defaultValue)
{
return new FieldCodec((ref ParseContext ctx) => ctx.ReadBool(), (ref WriteContext ctx, bool value) => ctx.WriteBool(value), CodedOutputStream.BoolSize, tag, defaultValue);
}
///
/// Retrieves a codec suitable for an int32 field with the given tag.
///
/// The tag.
/// The default value.
/// A codec for the given tag.
public static FieldCodec ForInt32(uint tag, int defaultValue)
{
return new FieldCodec((ref ParseContext ctx) => ctx.ReadInt32(), (ref WriteContext output, int value) => output.WriteInt32(value), CodedOutputStream.ComputeInt32Size, tag, defaultValue);
}
///
/// Retrieves a codec suitable for an sint32 field with the given tag.
///
/// The tag.
/// The default value.
/// A codec for the given tag.
public static FieldCodec ForSInt32(uint tag, int defaultValue)
{
return new FieldCodec((ref ParseContext ctx) => ctx.ReadSInt32(), (ref WriteContext output, int value) => output.WriteSInt32(value), CodedOutputStream.ComputeSInt32Size, tag, defaultValue);
}
///
/// Retrieves a codec suitable for a fixed32 field with the given tag.
///
/// The tag.
/// The default value.
/// A codec for the given tag.
public static FieldCodec ForFixed32(uint tag, uint defaultValue)
{
return new FieldCodec((ref ParseContext ctx) => ctx.ReadFixed32(), (ref WriteContext output, uint value) => output.WriteFixed32(value), 4, tag, defaultValue);
}
///
/// Retrieves a codec suitable for an sfixed32 field with the given tag.
///
/// The tag.
/// The default value.
/// A codec for the given tag.
public static FieldCodec ForSFixed32(uint tag, int defaultValue)
{
return new FieldCodec((ref ParseContext ctx) => ctx.ReadSFixed32(), (ref WriteContext output, int value) => output.WriteSFixed32(value), 4, tag, defaultValue);
}
///
/// Retrieves a codec suitable for a uint32 field with the given tag.
///
/// The tag.
/// The default value.
/// A codec for the given tag.
public static FieldCodec ForUInt32(uint tag, uint defaultValue)
{
return new FieldCodec((ref ParseContext ctx) => ctx.ReadUInt32(), (ref WriteContext output, uint value) => output.WriteUInt32(value), CodedOutputStream.ComputeUInt32Size, tag, defaultValue);
}
///
/// Retrieves a codec suitable for an int64 field with the given tag.
///
/// The tag.
/// The default value.
/// A codec for the given tag.
public static FieldCodec ForInt64(uint tag, long defaultValue)
{
return new FieldCodec((ref ParseContext ctx) => ctx.ReadInt64(), (ref WriteContext output, long value) => output.WriteInt64(value), CodedOutputStream.ComputeInt64Size, tag, defaultValue);
}
///
/// Retrieves a codec suitable for an sint64 field with the given tag.
///
/// The tag.
/// The default value.
/// A codec for the given tag.
public static FieldCodec ForSInt64(uint tag, long defaultValue)
{
return new FieldCodec((ref ParseContext ctx) => ctx.ReadSInt64(), (ref WriteContext output, long value) => output.WriteSInt64(value), CodedOutputStream.ComputeSInt64Size, tag, defaultValue);
}
///
/// Retrieves a codec suitable for a fixed64 field with the given tag.
///
/// The tag.
/// The default value.
/// A codec for the given tag.
public static FieldCodec ForFixed64(uint tag, ulong defaultValue)
{
return new FieldCodec((ref ParseContext ctx) => ctx.ReadFixed64(), (ref WriteContext output, ulong value) => output.WriteFixed64(value), 8, tag, defaultValue);
}
///
/// Retrieves a codec suitable for an sfixed64 field with the given tag.
///
/// The tag.
/// The default value.
/// A codec for the given tag.
public static FieldCodec ForSFixed64(uint tag, long defaultValue)
{
return new FieldCodec((ref ParseContext ctx) => ctx.ReadSFixed64(), (ref WriteContext output, long value) => output.WriteSFixed64(value), 8, tag, defaultValue);
}
///
/// Retrieves a codec suitable for a uint64 field with the given tag.
///
/// The tag.
/// The default value.
/// A codec for the given tag.
public static FieldCodec ForUInt64(uint tag, ulong defaultValue)
{
return new FieldCodec((ref ParseContext ctx) => ctx.ReadUInt64(), (ref WriteContext output, ulong value) => output.WriteUInt64(value), CodedOutputStream.ComputeUInt64Size, tag, defaultValue);
}
///
/// Retrieves a codec suitable for a float field with the given tag.
///
/// The tag.
/// The default value.
/// A codec for the given tag.
public static FieldCodec ForFloat(uint tag, float defaultValue)
{
return new FieldCodec((ref ParseContext ctx) => ctx.ReadFloat(), (ref WriteContext output, float value) => output.WriteFloat(value), CodedOutputStream.FloatSize, tag, defaultValue);
}
///
/// Retrieves a codec suitable for a double field with the given tag.
///
/// The tag.
/// The default value.
/// A codec for the given tag.
public static FieldCodec ForDouble(uint tag, double defaultValue)
{
return new FieldCodec((ref ParseContext ctx) => ctx.ReadDouble(), (ref WriteContext output, double value) => output.WriteDouble(value), CodedOutputStream.DoubleSize, tag, defaultValue);
}
// Enums are tricky. We can probably use expression trees to build these delegates automatically,
// but it's easy to generate the code for it.
///
/// Retrieves a codec suitable for an enum field with the given tag.
///
/// The tag.
/// A conversion function from to the enum type.
/// A conversion function from the enum type to .
/// The default value.
/// A codec for the given tag.
public static FieldCodec ForEnum(uint tag, Func toInt32, Func fromInt32, T defaultValue)
{
return new FieldCodec((ref ParseContext ctx) => fromInt32(
ctx.ReadEnum()),
(ref WriteContext output, T value) => output.WriteEnum(toInt32(value)),
value => CodedOutputStream.ComputeEnumSize(toInt32(value)), tag, defaultValue);
}
///
/// Retrieves a codec suitable for a message field with the given tag.
///
/// The tag.
/// A parser to use for the message type.
/// A codec for the given tag.
public static FieldCodec ForMessage(uint tag, MessageParser parser) where T : class, IMessage
{
return new FieldCodec(
(ref ParseContext ctx) =>
{
T message = parser.CreateTemplate();
ctx.ReadMessage(message);
return message;
},
(ref WriteContext output, T value) => output.WriteMessage(value),
(ref ParseContext ctx, ref T v) =>
{
if (v == null)
{
v = parser.CreateTemplate();
}
ctx.ReadMessage(v);
},
(ref T v, T v2) =>
{
if (v2 == null)
{
return false;
}
else if (v == null)
{
v = v2.Clone();
}
else
{
v.MergeFrom(v2);
}
return true;
},
message => CodedOutputStream.ComputeMessageSize(message), tag);
}
///
/// Retrieves a codec suitable for a group field with the given tag.
///
/// The start group tag.
/// The end group tag.
/// A parser to use for the group message type.
/// A codec for given tag
public static FieldCodec ForGroup(uint startTag, uint endTag, MessageParser parser) where T : class, IMessage
{
return new FieldCodec(
(ref ParseContext ctx) =>
{
T message = parser.CreateTemplate();
ctx.ReadGroup(message);
return message;
},
(ref WriteContext output, T value) => output.WriteGroup(value),
(ref ParseContext ctx, ref T v) =>
{
if (v == null)
{
v = parser.CreateTemplate();
}
ctx.ReadGroup(v);
},
(ref T v, T v2) =>
{
if (v2 == null)
{
return v == null;
}
else if (v == null)
{
v = v2.Clone();
}
else
{
v.MergeFrom(v2);
}
return true;
},
message => CodedOutputStream.ComputeGroupSize(message), startTag, endTag);
}
///
/// Creates a codec for a wrapper type of a class - which must be string or ByteString.
///
public static FieldCodec ForClassWrapper(uint tag) where T : class
{
var nestedCodec = WrapperCodecs.GetCodec();
return new FieldCodec(
(ref ParseContext ctx) => WrapperCodecs.Read(ref ctx, nestedCodec),
(ref WriteContext output, T value) => WrapperCodecs.Write(ref output, value, nestedCodec),
(ref ParseContext ctx, ref T v) => v = WrapperCodecs.Read(ref ctx, nestedCodec),
(ref T v, T v2) => { v = v2; return v == null; },
value => WrapperCodecs.CalculateSize(value, nestedCodec),
tag, 0,
null); // Default value for the wrapper
}
///
/// Creates a codec for a wrapper type of a struct - which must be Int32, Int64, UInt32, UInt64,
/// Bool, Single or Double.
///
public static FieldCodec ForStructWrapper(uint tag) where T : struct
{
var nestedCodec = WrapperCodecs.GetCodec();
return new FieldCodec(
WrapperCodecs.GetReader(),
(ref WriteContext output, T? value) => WrapperCodecs.Write(ref output, value.Value, nestedCodec),
(ref ParseContext ctx, ref T? v) => v = WrapperCodecs.Read(ref ctx, nestedCodec),
(ref T? v, T? v2) => { if (v2.HasValue) { v = v2; } return v.HasValue; },
value => value == null ? 0 : WrapperCodecs.CalculateSize(value.Value, nestedCodec),
tag, 0,
null); // Default value for the wrapper
}
///
/// Helper code to create codecs for wrapper types.
///
///
/// Somewhat ugly with all the static methods, but the conversions involved to/from nullable types make it
/// slightly tricky to improve. So long as we keep the public API (ForClassWrapper, ForStructWrapper) in place,
/// we can refactor later if we come up with something cleaner.
///
private static class WrapperCodecs
{
private static readonly Dictionary Codecs = new Dictionary
{
{ typeof(bool), ForBool(WireFormat.MakeTag(WrappersReflection.WrapperValueFieldNumber, WireFormat.WireType.Varint)) },
{ typeof(int), ForInt32(WireFormat.MakeTag(WrappersReflection.WrapperValueFieldNumber, WireFormat.WireType.Varint)) },
{ typeof(long), ForInt64(WireFormat.MakeTag(WrappersReflection.WrapperValueFieldNumber, WireFormat.WireType.Varint)) },
{ typeof(uint), ForUInt32(WireFormat.MakeTag(WrappersReflection.WrapperValueFieldNumber, WireFormat.WireType.Varint)) },
{ typeof(ulong), ForUInt64(WireFormat.MakeTag(WrappersReflection.WrapperValueFieldNumber, WireFormat.WireType.Varint)) },
{ typeof(float), ForFloat(WireFormat.MakeTag(WrappersReflection.WrapperValueFieldNumber, WireFormat.WireType.Fixed32)) },
{ typeof(double), ForDouble(WireFormat.MakeTag(WrappersReflection.WrapperValueFieldNumber, WireFormat.WireType.Fixed64)) },
{ typeof(string), ForString(WireFormat.MakeTag(WrappersReflection.WrapperValueFieldNumber, WireFormat.WireType.LengthDelimited)) },
{ typeof(ByteString), ForBytes(WireFormat.MakeTag(WrappersReflection.WrapperValueFieldNumber, WireFormat.WireType.LengthDelimited)) }
};
private static readonly Dictionary Readers = new Dictionary
{
// TODO: Provide more optimized readers.
{ typeof(bool), (ValueReader)ParsingPrimitivesWrappers.ReadBoolWrapper },
{ typeof(int), (ValueReader)ParsingPrimitivesWrappers.ReadInt32Wrapper },
{ typeof(long), (ValueReader)ParsingPrimitivesWrappers.ReadInt64Wrapper },
{ typeof(uint), (ValueReader)ParsingPrimitivesWrappers.ReadUInt32Wrapper },
{ typeof(ulong), (ValueReader)ParsingPrimitivesWrappers.ReadUInt64Wrapper },
{ typeof(float), BitConverter.IsLittleEndian ?
(ValueReader)ParsingPrimitivesWrappers.ReadFloatWrapperLittleEndian :
(ValueReader)ParsingPrimitivesWrappers.ReadFloatWrapperSlow },
{ typeof(double), BitConverter.IsLittleEndian ?
(ValueReader)ParsingPrimitivesWrappers.ReadDoubleWrapperLittleEndian :
(ValueReader)ParsingPrimitivesWrappers.ReadDoubleWrapperSlow },
// `string` and `ByteString` less performance-sensitive. Do not implement for now.
{ typeof(string), null },
{ typeof(ByteString), null },
};
///
/// Returns a field codec which effectively wraps a value of type T in a message.
///
///
internal static FieldCodec GetCodec()
{
object value;
if (!Codecs.TryGetValue(typeof(T), out value))
{
throw new InvalidOperationException("Invalid type argument requested for wrapper codec: " + typeof(T));
}
return (FieldCodec) value;
}
internal static ValueReader GetReader() where T : struct
{
object value;
if (!Readers.TryGetValue(typeof(T), out value))
{
throw new InvalidOperationException("Invalid type argument requested for wrapper reader: " + typeof(T));
}
if (value == null)
{
// Return default unoptimized reader for the wrapper type.
var nestedCoded = GetCodec();
return (ref ParseContext ctx) => Read(ref ctx, nestedCoded);
}
// Return optimized read for the wrapper type.
return (ValueReader)value;
}
[SecuritySafeCritical]
internal static T Read(ref ParseContext ctx, FieldCodec codec)
{
int length = ctx.ReadLength();
int oldLimit = SegmentedBufferHelper.PushLimit(ref ctx.state, length);
uint tag;
T value = codec.DefaultValue;
while ((tag = ctx.ReadTag()) != 0)
{
if (tag == codec.Tag)
{
value = codec.Read(ref ctx);
}
else
{
ParsingPrimitivesMessages.SkipLastField(ref ctx.buffer, ref ctx.state);
}
}
ParsingPrimitivesMessages.CheckReadEndOfStreamTag(ref ctx.state);
SegmentedBufferHelper.PopLimit(ref ctx.state, oldLimit);
return value;
}
internal static void Write(ref WriteContext ctx, T value, FieldCodec codec)
{
ctx.WriteLength(codec.CalculateSizeWithTag(value));
codec.WriteTagAndValue(ref ctx, value);
}
internal static int CalculateSize(T value, FieldCodec codec)
{
int fieldLength = codec.CalculateSizeWithTag(value);
return CodedOutputStream.ComputeLengthSize(fieldLength) + fieldLength;
}
}
}
internal delegate TValue ValueReader(ref ParseContext ctx);
internal delegate void ValueWriter(ref WriteContext ctx, T value);
///
///
/// An encode/decode pair for a single field. This effectively encapsulates
/// all the information needed to read or write the field value from/to a coded
/// stream.
///
///
/// This class is public and has to be as it is used by generated code, but its public
/// API is very limited - just what the generated code needs to call directly.
///
///
///
/// This never writes default values to the stream, and does not address "packedness"
/// in repeated fields itself, other than to know whether or not the field *should* be packed.
///
public sealed class FieldCodec
{
private static readonly EqualityComparer EqualityComparer = ProtobufEqualityComparers.GetEqualityComparer();
private static readonly T DefaultDefault;
// Only non-nullable value types support packing. This is the simplest way of detecting that.
private static readonly bool TypeSupportsPacking = default(T) != null;
///
/// Merges an input stream into a value
///
internal delegate void InputMerger(ref ParseContext ctx, ref T value);
///
/// Merges a value into a reference to another value, returning a boolean if the value was set
///
internal delegate bool ValuesMerger(ref T value, T other);
static FieldCodec()
{
if (typeof(T) == typeof(string))
{
DefaultDefault = (T)(object)"";
}
else if (typeof(T) == typeof(ByteString))
{
DefaultDefault = (T)(object)ByteString.Empty;
}
// Otherwise it's the default value of the CLR type
}
internal static bool IsPackedRepeatedField(uint tag) =>
TypeSupportsPacking && WireFormat.GetTagWireType(tag) == WireFormat.WireType.LengthDelimited;
internal bool PackedRepeatedField { get; }
///
/// Returns a delegate to write a value (unconditionally) to a coded output stream.
///
internal ValueWriter ValueWriter { get; }
///
/// Returns the size calculator for just a value.
///
internal Func ValueSizeCalculator { get; }
///
/// Returns a delegate to read a value from a coded input stream. It is assumed that
/// the stream is already positioned on the appropriate tag.
///
internal ValueReader ValueReader { get; }
///
/// Returns a delegate to merge a value from a coded input stream.
/// It is assumed that the stream is already positioned on the appropriate tag
///
internal InputMerger ValueMerger { get; }
///
/// Returns a delegate to merge two values together.
///
internal ValuesMerger FieldMerger { get; }
///
/// Returns the fixed size for an entry, or 0 if sizes vary.
///
internal int FixedSize { get; }
///
/// Gets the tag of the codec.
///
///
/// The tag of the codec.
///
internal uint Tag { get; }
///
/// Gets the end tag of the codec or 0 if there is no end tag
///
///
/// The end tag of the codec.
///
internal uint EndTag { get; }
///
/// Default value for this codec. Usually the same for every instance of the same type, but
/// for string/ByteString wrapper fields the codec's default value is null, whereas for
/// other string/ByteString fields it's "" or ByteString.Empty.
///
///
/// The default value of the codec's type.
///
internal T DefaultValue { get; }
private readonly int tagSize;
internal FieldCodec(
ValueReader reader,
ValueWriter writer,
int fixedSize,
uint tag,
T defaultValue) : this(reader, writer, _ => fixedSize, tag, defaultValue)
{
FixedSize = fixedSize;
}
internal FieldCodec(
ValueReader reader,
ValueWriter writer,
Func sizeCalculator,
uint tag,
T defaultValue) : this(reader, writer, (ref ParseContext ctx, ref T v) => v = reader(ref ctx), (ref T v, T v2) => { v = v2; return true; }, sizeCalculator, tag, 0, defaultValue)
{
}
internal FieldCodec(
ValueReader reader,
ValueWriter writer,
InputMerger inputMerger,
ValuesMerger valuesMerger,
Func sizeCalculator,
uint tag,
uint endTag = 0) : this(reader, writer, inputMerger, valuesMerger, sizeCalculator, tag, endTag, DefaultDefault)
{
}
internal FieldCodec(
ValueReader reader,
ValueWriter writer,
InputMerger inputMerger,
ValuesMerger valuesMerger,
Func sizeCalculator,
uint tag,
uint endTag,
T defaultValue)
{
ValueReader = reader;
ValueWriter = writer;
ValueMerger = inputMerger;
FieldMerger = valuesMerger;
ValueSizeCalculator = sizeCalculator;
FixedSize = 0;
Tag = tag;
EndTag = endTag;
DefaultValue = defaultValue;
tagSize = CodedOutputStream.ComputeRawVarint32Size(tag);
if (endTag != 0)
tagSize += CodedOutputStream.ComputeRawVarint32Size(endTag);
// Detect packed-ness once, so we can check for it within RepeatedField.
PackedRepeatedField = IsPackedRepeatedField(tag);
}
///
/// Write a tag and the given value, *if* the value is not the default.
///
public void WriteTagAndValue(CodedOutputStream output, T value)
{
WriteContext.Initialize(output, out WriteContext ctx);
try
{
WriteTagAndValue(ref ctx, value);
}
finally
{
ctx.CopyStateTo(output);
}
//if (!IsDefault(value))
//{
// output.WriteTag(Tag);
// ValueWriter(output, value);
// if (EndTag != 0)
// {
// output.WriteTag(EndTag);
// }
//}
}
///
/// Write a tag and the given value, *if* the value is not the default.
///
public void WriteTagAndValue(ref WriteContext ctx, T value)
{
if (!IsDefault(value))
{
ctx.WriteTag(Tag);
ValueWriter(ref ctx, value);
if (EndTag != 0)
{
ctx.WriteTag(EndTag);
}
}
}
///
/// Reads a value of the codec type from the given .
///
/// The input stream to read from.
/// The value read from the stream.
public T Read(CodedInputStream input)
{
ParseContext.Initialize(input, out ParseContext ctx);
try
{
return ValueReader(ref ctx);
}
finally
{
ctx.CopyStateTo(input);
}
}
///
/// Reads a value of the codec type from the given .
///
/// The parse context to read from.
/// The value read.
public T Read(ref ParseContext ctx)
{
return ValueReader(ref ctx);
}
///
/// Calculates the size required to write the given value, with a tag,
/// if the value is not the default.
///
public int CalculateSizeWithTag(T value) => IsDefault(value) ? 0 : ValueSizeCalculator(value) + tagSize;
private bool IsDefault(T value) => EqualityComparer.Equals(value, DefaultValue);
}
}