#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 System; using System.Collections.Generic; namespace Google.Protobuf { /// /// Factory methods for . /// public static class FieldCodec { // TODO: Avoid the "dual hit" of lambda expressions: create open delegates instead. (At least test...) public static FieldCodec ForString(uint tag) { return new FieldCodec(input => input.ReadString(), (output, value) => output.WriteString(value), CodedOutputStream.ComputeStringSize, tag); } public static FieldCodec ForBytes(uint tag) { return new FieldCodec(input => input.ReadBytes(), (output, value) => output.WriteBytes(value), CodedOutputStream.ComputeBytesSize, tag); } public static FieldCodec ForBool(uint tag) { return new FieldCodec(input => input.ReadBool(), (output, value) => output.WriteBool(value), CodedOutputStream.ComputeBoolSize, tag); } public static FieldCodec ForInt32(uint tag) { return new FieldCodec(input => input.ReadInt32(), (output, value) => output.WriteInt32(value), CodedOutputStream.ComputeInt32Size, tag); } public static FieldCodec ForSInt32(uint tag) { return new FieldCodec(input => input.ReadSInt32(), (output, value) => output.WriteSInt32(value), CodedOutputStream.ComputeSInt32Size, tag); } public static FieldCodec ForFixed32(uint tag) { return new FieldCodec(input => input.ReadFixed32(), (output, value) => output.WriteFixed32(value), 4, tag); } public static FieldCodec ForSFixed32(uint tag) { return new FieldCodec(input => input.ReadSFixed32(), (output, value) => output.WriteSFixed32(value), 4, tag); } public static FieldCodec ForUInt32(uint tag) { return new FieldCodec(input => input.ReadUInt32(), (output, value) => output.WriteUInt32(value), CodedOutputStream.ComputeUInt32Size, tag); } public static FieldCodec ForInt64(uint tag) { return new FieldCodec(input => input.ReadInt64(), (output, value) => output.WriteInt64(value), CodedOutputStream.ComputeInt64Size, tag); } public static FieldCodec ForSInt64(uint tag) { return new FieldCodec(input => input.ReadSInt64(), (output, value) => output.WriteSInt64(value), CodedOutputStream.ComputeSInt64Size, tag); } public static FieldCodec ForFixed64(uint tag) { return new FieldCodec(input => input.ReadFixed64(), (output, value) => output.WriteFixed64(value), 8, tag); } public static FieldCodec ForSFixed64(uint tag) { return new FieldCodec(input => input.ReadSFixed64(), (output, value) => output.WriteSFixed64(value), 8, tag); } public static FieldCodec ForUInt64(uint tag) { return new FieldCodec(input => input.ReadUInt64(), (output, value) => output.WriteUInt64(value), CodedOutputStream.ComputeUInt64Size, tag); } public static FieldCodec ForFloat(uint tag) { return new FieldCodec(input => input.ReadFloat(), (output, value) => output.WriteFloat(value), CodedOutputStream.ComputeFloatSize, tag); } public static FieldCodec ForDouble(uint tag) { return new FieldCodec(input => input.ReadDouble(), (output, value) => output.WriteDouble(value), CodedOutputStream.ComputeDoubleSize, tag); } // Enums are tricky. We can probably use expression trees to build these delegates automatically, // but it's easy to generate the code for it. public static FieldCodec ForEnum(uint tag, Func toInt32, Func fromInt32) { return new FieldCodec(input => fromInt32( input.ReadEnum()), (output, value) => output.WriteEnum(toInt32(value)), value => CodedOutputStream.ComputeEnumSize(toInt32(value)), tag); } public static FieldCodec ForMessage(uint tag, MessageParser parser) where T : IMessage { return new FieldCodec(input => { T message = parser.CreateTemplate(); input.ReadMessage(message); return message; }, (output, value) => output.WriteMessage(value), message => CodedOutputStream.ComputeMessageSize(message), tag); } /// /// 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( input => WrapperCodecs.Read(input, nestedCodec), (output, value) => WrapperCodecs.Write(output, value, nestedCodec), value => WrapperCodecs.CalculateSize(value, nestedCodec), tag, 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( input => WrapperCodecs.Read(input, nestedCodec), (output, value) => WrapperCodecs.Write(output, value.Value, nestedCodec), value => value == null ? 0 : WrapperCodecs.CalculateSize(value.Value, nestedCodec), tag, 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 { // All the field numbers are the same (1). private const int WrapperValueFieldNumber = Google.Protobuf.WellKnownTypes.Int32Value.ValueFieldNumber; private static readonly Dictionary Codecs = new Dictionary { { typeof(bool), ForBool(WireFormat.MakeTag(WrapperValueFieldNumber, WireFormat.WireType.Varint)) }, { typeof(int), ForInt32(WireFormat.MakeTag(WrapperValueFieldNumber, WireFormat.WireType.Varint)) }, { typeof(long), ForInt64(WireFormat.MakeTag(WrapperValueFieldNumber, WireFormat.WireType.Varint)) }, { typeof(uint), ForUInt32(WireFormat.MakeTag(WrapperValueFieldNumber, WireFormat.WireType.Varint)) }, { typeof(ulong), ForUInt64(WireFormat.MakeTag(WrapperValueFieldNumber, WireFormat.WireType.Varint)) }, { typeof(float), ForFloat(WireFormat.MakeTag(WrapperValueFieldNumber, WireFormat.WireType.Fixed32)) }, { typeof(double), ForDouble(WireFormat.MakeTag(WrapperValueFieldNumber, WireFormat.WireType.Fixed64)) }, { typeof(string), ForString(WireFormat.MakeTag(WrapperValueFieldNumber, WireFormat.WireType.LengthDelimited)) }, { typeof(ByteString), ForBytes(WireFormat.MakeTag(WrapperValueFieldNumber, WireFormat.WireType.LengthDelimited)) } }; /// /// 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 T Read(CodedInputStream input, FieldCodec codec) { int length = input.ReadLength(); int oldLimit = input.PushLimit(length); uint tag; T value = codec.DefaultValue; while (input.ReadTag(out tag)) { if (tag == 0) { throw InvalidProtocolBufferException.InvalidTag(); } if (tag == codec.Tag) { value = codec.Read(input); } if (WireFormat.IsEndGroupTag(tag)) { break; } } input.CheckLastTagWas(0); input.PopLimit(oldLimit); return value; } internal static void Write(CodedOutputStream output, T value, FieldCodec codec) { output.WriteLength(codec.CalculateSizeWithTag(value)); codec.WriteTagAndValue(output, value); } internal static int CalculateSize(T value, FieldCodec codec) { int fieldLength = codec.CalculateSizeWithTag(value); return CodedOutputStream.ComputeLengthSize(fieldLength) + fieldLength; } } } /// /// 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 never writes default values to the stream, and is not currently designed /// to play well with packed arrays. /// public sealed class FieldCodec { private static readonly T DefaultDefault; 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 } private static Func CreateDefaultValueCheck(Func check) { return (Func)(object)check; } private readonly Func reader; private readonly Action writer; private readonly Func sizeCalculator; private readonly uint tag; private readonly int tagSize; private readonly int fixedSize; // 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. private readonly T defaultValue; internal FieldCodec( Func reader, Action writer, Func sizeCalculator, uint tag) : this(reader, writer, sizeCalculator, tag, DefaultDefault) { } internal FieldCodec( Func reader, Action writer, Func sizeCalculator, uint tag, T defaultValue) { this.reader = reader; this.writer = writer; this.sizeCalculator = sizeCalculator; this.fixedSize = 0; this.tag = tag; this.defaultValue = defaultValue; tagSize = CodedOutputStream.ComputeRawVarint32Size(tag); } internal FieldCodec( Func reader, Action writer, int fixedSize, uint tag) { this.reader = reader; this.writer = writer; this.sizeCalculator = _ => fixedSize; this.fixedSize = fixedSize; this.tag = tag; tagSize = CodedOutputStream.ComputeRawVarint32Size(tag); } /// /// Returns the size calculator for just a value. /// internal Func ValueSizeCalculator { get { return sizeCalculator; } } /// /// Returns a delegate to write a value (unconditionally) to a coded output stream. /// internal Action ValueWriter { get { return writer; } } /// /// 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 Func ValueReader { get { return reader; } } /// /// Returns the fixed size for an entry, or 0 if sizes vary. /// internal int FixedSize { get { return fixedSize; } } public uint Tag { get { return tag; } } public T DefaultValue { get { return defaultValue; } } /// /// Write a tag and the given value, *if* the value is not the default. /// public void WriteTagAndValue(CodedOutputStream output, T value) { if (!IsDefault(value)) { output.WriteTag(tag); writer(output, value); } } public T Read(CodedInputStream input) { return reader(input); } /// /// Calculates the size required to write the given value, with a tag, /// if the value is not the default. /// public int CalculateSizeWithTag(T value) { return IsDefault(value) ? 0 : sizeCalculator(value) + tagSize; } private bool IsDefault(T value) { return EqualityComparer.Default.Equals(value, defaultValue); } } }