public void AddEntriesFrom_CodedInputStream()
        {
            // map will have string key and string value
            var keyTag   = WireFormat.MakeTag(1, WireFormat.WireType.LengthDelimited);
            var valueTag = WireFormat.MakeTag(2, WireFormat.WireType.LengthDelimited);

            var memoryStream = new MemoryStream();
            var output       = new CodedOutputStream(memoryStream);

            output.WriteLength(20);  // total of keyTag + key + valueTag + value
            output.WriteTag(keyTag);
            output.WriteString("the_key");
            output.WriteTag(valueTag);
            output.WriteString("the_value");
            output.Flush();

            var field    = new MapField <string, string>();
            var mapCodec = new MapField <string, string> .Codec(FieldCodec.ForString(keyTag, ""), FieldCodec.ForString(valueTag, ""), 10);

            var input = new CodedInputStream(memoryStream.ToArray());

            // test the legacy overload of AddEntriesFrom that takes a CodedInputStream
            field.AddEntriesFrom(input, mapCodec);
            CollectionAssert.AreEquivalent(new[] { "the_key" }, field.Keys);
            CollectionAssert.AreEquivalent(new[] { "the_value" }, field.Values);
            Assert.IsTrue(input.IsAtEnd);
        }
 /// <summary>
 /// Generate IL code that write tag of field.<br/>
 /// ref WriteContext is at argument 1(OpCodes.Ldarg_1).<br/>
 /// It should be empty in the stack after codes.
 /// </summary>
 /// <param name="ilGenerator">IL generator.</param>
 /// <param name="fieldNumber">Field Number.</param>
 protected virtual void GenerateWriteTagCode(ILGenerator ilGenerator, int fieldNumber)
 {
     //Write tag
     ilGenerator.Emit(OpCodes.Ldarg_1);
     ilGenerator.Emit(OpCodes.Ldc_I4, (int)WireFormat.MakeTag(fieldNumber, WireType));
     ilGenerator.Emit(OpCodes.Call, typeof(WriteContext).GetMethod("WriteTag", BindingFlags.Instance | BindingFlags.Public, null, new Type[] { typeof(uint) }, null));
 }
        public void AddEntriesFrom_CodedInputStream_MissingKey()
        {
            // map will have string key and string value
            var keyTag   = WireFormat.MakeTag(1, WireFormat.WireType.LengthDelimited);
            var valueTag = WireFormat.MakeTag(2, WireFormat.WireType.LengthDelimited);

            var memoryStream = new MemoryStream();
            var output       = new CodedOutputStream(memoryStream);

            output.WriteLength(11);  // total of valueTag + value
            output.WriteTag(valueTag);
            output.WriteString("the_value");
            output.Flush();

            Console.WriteLine(BitConverter.ToString(memoryStream.ToArray()));

            var field    = new MapField <string, string>();
            var mapCodec = new MapField <string, string> .Codec(FieldCodec.ForString(keyTag, ""), FieldCodec.ForString(valueTag, ""), 10);

            var input = new CodedInputStream(memoryStream.ToArray());

            field.AddEntriesFrom(input, mapCodec);
            CollectionAssert.AreEquivalent(new[] { "" }, field.Keys);
            CollectionAssert.AreEquivalent(new[] { "the_value" }, field.Values);
            Assert.IsTrue(input.IsAtEnd);
        }
示例#4
0
        public void TestPackedRepeatedFieldCollectionNonDivisibleLength()
        {
            uint tag    = WireFormat.MakeTag(10, WireFormat.WireType.LengthDelimited);
            var  codec  = FieldCodec.ForFixed32(tag);
            var  stream = new MemoryStream();
            var  output = new CodedOutputStream(stream);

            output.WriteTag(tag);
            output.WriteString("A long string");
            output.WriteTag(codec.Tag);
            output.WriteRawVarint32((uint)codec.FixedSize - 1); // Length not divisible by FixedSize
            output.WriteFixed32(uint.MaxValue);
            output.Flush();
            stream.Position = 0;

            var input = new CodedInputStream(stream);

            input.ReadTag();
            input.ReadString();
            input.ReadTag();
            var field = new RepeatedField <uint>();

            Assert.Throws <InvalidProtocolBufferException>(() => field.AddEntriesFrom(input, codec));

            // Collection was not pre-initialized
            Assert.AreEqual(0, field.Count);
        }
示例#5
0
        public void UnknownFieldInWrapperInt64SlowPath()
        {
            var stream     = new MemoryStream();
            var output     = new CodedOutputStream(stream);
            var wrapperTag = WireFormat.MakeTag(TestWellKnownTypes.Int64FieldFieldNumber, WireFormat.WireType.LengthDelimited);
            var unknownTag = WireFormat.MakeTag(15, WireFormat.WireType.Varint);
            var valueTag   = WireFormat.MakeTag(Int64Value.ValueFieldNumber, WireFormat.WireType.Varint);

            output.WriteTag(wrapperTag);
            // Wrapper message is too short to be used on the wrapper fast-path.
            output.WriteLength(4);            // unknownTag + value 5 + valueType + value 6, each 1 byte
            output.WriteTag(unknownTag);
            output.WriteInt64((int)valueTag); // Sneakily "pretend" it's a tag when it's really a value
            output.WriteTag(valueTag);
            output.WriteInt64(6);

            output.Flush();
            Assert.Less(stream.Length, 12); // tag (1 byte) + length (1 byte) + message
            stream.Position = 0;

            MessageParsingHelpers.AssertReadingMessage(
                TestWellKnownTypes.Parser,
                stream.ToArray(),
                message => Assert.AreEqual(6L, message.Int64Field));
        }
示例#6
0
        public void AddEntriesFrom_NonPackedInt32()
        {
            uint nonPackedTag = WireFormat.MakeTag(10, WireFormat.WireType.Varint);
            var  stream       = new MemoryStream();
            var  output       = new CodedOutputStream(stream);

            output.WriteTag(nonPackedTag);
            output.WriteInt32(10);
            output.WriteTag(nonPackedTag);
            output.WriteInt32(999);
            output.WriteTag(nonPackedTag);
            output.WriteInt32(-1000); // Just for variety...
            output.Flush();
            stream.Position = 0;

            // Deliberately "expecting" a packed tag, but we detect that the data is
            // actually not packed.
            uint packedTag = WireFormat.MakeTag(10, WireFormat.WireType.LengthDelimited);
            var  field     = new RepeatedField <int>();
            var  input     = new CodedInputStream(stream);

            input.AssertNextTag(nonPackedTag);
            field.AddEntriesFrom(input, FieldCodec.ForInt32(packedTag));
            CollectionAssert.AreEqual(new[] { 10, 999, -1000 }, field);
            Assert.IsTrue(input.IsAtEnd);
        }
示例#7
0
        public void WriteTo_Message()
        {
            var message1 = new ForeignMessage {
                C = 20
            };
            var message2 = new ForeignMessage {
                C = 25
            };
            uint tag   = WireFormat.MakeTag(10, WireFormat.WireType.LengthDelimited);
            var  field = new RepeatedField <ForeignMessage> {
                message1, message2
            };
            var stream = new MemoryStream();
            var output = new CodedOutputStream(stream);

            field.WriteTo(output, FieldCodec.ForMessage(tag, ForeignMessage.Parser));
            output.Flush();
            stream.Position = 0;

            var input = new CodedInputStream(stream);

            input.AssertNextTag(tag);
            Assert.AreEqual(message1, input.ReadMessage(ForeignMessage.Parser));
            input.AssertNextTag(tag);
            Assert.AreEqual(message2, input.ReadMessage(ForeignMessage.Parser));
            Assert.IsTrue(input.IsAtEnd);
        }
示例#8
0
        public void UnknownFieldInWrapperInt64FastPath()
        {
            var stream     = new MemoryStream();
            var output     = new CodedOutputStream(stream);
            var wrapperTag = WireFormat.MakeTag(TestWellKnownTypes.Int64FieldFieldNumber, WireFormat.WireType.LengthDelimited);
            var unknownTag = WireFormat.MakeTag(15, WireFormat.WireType.Varint);
            var valueTag   = WireFormat.MakeTag(Int64Value.ValueFieldNumber, WireFormat.WireType.Varint);

            output.WriteTag(wrapperTag);
            // Wrapper message is just long enough - 10 bytes - to use the wrapper fast-path.
            output.WriteLength(11);           // unknownTag + value 5 + valueType, each 1 byte, + value 0xfffffffffffff, 8 bytes
            output.WriteTag(unknownTag);
            output.WriteInt64((int)valueTag); // Sneakily "pretend" it's a tag when it's really a value
            output.WriteTag(valueTag);
            output.WriteInt64(0xfffffffffffffL);

            output.Flush();
            Assert.AreEqual(13, stream.Length); // tag (1 byte) + length (1 byte) + message (11 bytes)
            stream.Position = 0;

            MessageParsingHelpers.AssertReadingMessage(
                TestWellKnownTypes.Parser,
                stream.ToArray(),
                message => Assert.AreEqual(0xfffffffffffffL, message.Int64Field));
        }
示例#9
0
        public void AddEntriesFrom_Message()
        {
            var message1 = new ForeignMessage {
                C = 2000
            };
            var message2 = new ForeignMessage {
                C = -250
            };

            uint tag    = WireFormat.MakeTag(10, WireFormat.WireType.LengthDelimited);
            var  stream = new MemoryStream();
            var  output = new CodedOutputStream(stream);

            output.WriteTag(tag);
            output.WriteMessage(message1);
            output.WriteTag(tag);
            output.WriteMessage(message2);
            output.Flush();
            stream.Position = 0;

            var field = new RepeatedField <ForeignMessage>();
            var input = new CodedInputStream(stream);

            input.AssertNextTag(tag);
            field.AddEntriesFrom(input, FieldCodec.ForMessage(tag, ForeignMessage.Parser));
            CollectionAssert.AreEqual(new[] { message1, message2 }, field);
            Assert.IsTrue(input.IsAtEnd);
        }
示例#10
0
        public void TestNegativeEnumArray()
        {
            int arraySize = 1 + 1 + (11 * 5);
            int msgSize   = arraySize;

            byte[]            bytes  = new byte[msgSize];
            CodedOutputStream output = new CodedOutputStream(bytes);
            uint tag = WireFormat.MakeTag(8, WireFormat.WireType.Varint);

            for (int i = 0; i >= -5; i--)
            {
                output.WriteTag(tag);
                output.WriteEnum(i);
            }

            Assert.AreEqual(0, output.SpaceLeft);

            CodedInputStream input = new CodedInputStream(bytes);

            tag = input.ReadTag();

            RepeatedField <SampleEnum> values = new RepeatedField <SampleEnum>();

            values.AddEntriesFrom(input, FieldCodec.ForEnum(tag, x => (int)x, x => (SampleEnum)x));

            Assert.AreEqual(6, values.Count);
            Assert.AreEqual(SampleEnum.None, values[0]);
            Assert.AreEqual(((SampleEnum)(-1)), values[1]);
            Assert.AreEqual(SampleEnum.NegativeValue, values[2]);
            Assert.AreEqual(((SampleEnum)(-3)), values[3]);
            Assert.AreEqual(((SampleEnum)(-4)), values[4]);
            Assert.AreEqual(((SampleEnum)(-5)), values[5]);
        }
示例#11
0
        public void AddEntriesFrom_PackedInt32()
        {
            uint packedTag = WireFormat.MakeTag(10, WireFormat.WireType.LengthDelimited);
            var  stream    = new MemoryStream();
            var  output    = CodedOutputStream.CreateInstance(stream);
            var  length    = CodedOutputStream.ComputeInt32Size(10)
                             + CodedOutputStream.ComputeInt32Size(999)
                             + CodedOutputStream.ComputeInt32Size(-1000);

            output.WriteTag(packedTag);
            output.WriteRawVarint32((uint)length);
            output.WriteInt32(10);
            output.WriteInt32(999);
            output.WriteInt32(-1000);
            output.Flush();
            stream.Position = 0;

            // Deliberately "expecting" a non-packed tag, but we detect that the data is
            // actually packed.
            uint nonPackedTag = WireFormat.MakeTag(10, WireFormat.WireType.LengthDelimited);
            var  field        = new RepeatedField <int>();
            var  input        = CodedInputStream.CreateInstance(stream);

            input.AssertNextTag(packedTag);
            field.AddEntriesFrom(input, FieldCodec.ForInt32(nonPackedTag));
            CollectionAssert.AreEqual(new[] { 10, 999, -1000 }, field);
            Assert.IsTrue(input.IsAtEnd);
        }
示例#12
0
        public void MergingCornerCase()
        {
            var message = new TestWellKnownTypes {
                Int32Field = 5
            };

            // Create a byte array which has the data of an Int32Value explicitly containing a value of 0.
            // This wouldn't normally happen.
            byte[] bytes;
            var    wrapperTag = WireFormat.MakeTag(TestWellKnownTypes.Int32FieldFieldNumber, WireFormat.WireType.LengthDelimited);
            var    valueTag   = WireFormat.MakeTag(Int32Value.ValueFieldNumber, WireFormat.WireType.Varint);

            using (var stream = new MemoryStream())
            {
                var coded = new CodedOutputStream(stream);
                coded.WriteTag(wrapperTag);
                coded.WriteLength(2); // valueTag + a value 0, each one byte
                coded.WriteTag(valueTag);
                coded.WriteInt32(0);
                coded.Flush();
                bytes = stream.ToArray();
            }

            message.MergeFrom(bytes);
            // A normal implementation would have 0 now, as the explicit default would have been overwritten the 5.
            Assert.AreEqual(5, message.Int32Field);
        }
示例#13
0
        public void TestPackedRepeatedFieldCollectionNotAllocatedWhenLengthExceedsBuffer()
        {
            uint tag    = WireFormat.MakeTag(10, WireFormat.WireType.LengthDelimited);
            var  codec  = FieldCodec.ForFixed32(tag);
            var  stream = new MemoryStream();
            var  output = new CodedOutputStream(stream);

            output.WriteTag(tag);
            output.WriteString("A long string");
            output.WriteTag(codec.Tag);
            output.WriteRawVarint32((uint)codec.FixedSize);
            // Note that there is no content for the packed field.
            // The field length exceeds the remaining length of content.
            output.Flush();
            stream.Position = 0;

            var input = new CodedInputStream(stream);

            input.ReadTag();
            input.ReadString();
            input.ReadTag();
            var field = new RepeatedField <uint>();

            Assert.Throws <InvalidProtocolBufferException>(() => field.AddEntriesFrom(input, codec));

            // Collection was not pre-initialized
            Assert.AreEqual(0, field.Count);
        }
示例#14
0
        private static void AssertTagOk(int field, WireType wireType)
        {
            var tag = WireFormat.MakeTag(field, wireType);

            Assert.Equal(field, WireFormat.GetFieldNumber(tag));
            Assert.Equal(wireType, WireFormat.GetWireType(tag));
            Assert.Equal(wireType, (WireType)(tag & 7));
            Assert.Equal(field, (int)(tag >> 3));
        }
示例#15
0
        public void CalculateSize_FixedSizeNonPacked()
        {
            var list = new RepeatedField <int> {
                1, 500, 1
            };
            var tag = WireFormat.MakeTag(1, WireFormat.WireType.Fixed32);

            // 5 bytes for the each entry
            Assert.AreEqual(15, list.CalculateSize(FieldCodec.ForSFixed32(tag)));
        }
示例#16
0
        public void CalculateSize_FixedSizePacked()
        {
            var list = new RepeatedField <int> {
                1, 500, 1
            };
            var tag = WireFormat.MakeTag(1, WireFormat.WireType.LengthDelimited);

            // 1 byte for the tag, 1 byte for the length, 4 bytes per entry
            Assert.AreEqual(14, list.CalculateSize(FieldCodec.ForSFixed32(tag)));
        }
示例#17
0
        public void CalculateSize_VariableSizeNonPacked()
        {
            var list = new RepeatedField <int> {
                1, 500, 1
            };
            var tag = WireFormat.MakeTag(1, WireFormat.WireType.Varint);

            // 2 bytes for the first entry, 3 bytes for the second, 2 bytes for the third
            Assert.AreEqual(7, list.CalculateSize(FieldCodec.ForInt32(tag)));
        }
        private void GenerateBuilderParsingMethods(TextGenerator writer)
        {
            List <FieldDescriptor> sortedFields = new List <FieldDescriptor>(Descriptor.Fields);

            sortedFields.Sort((f1, f2) => f1.FieldNumber.CompareTo(f2.FieldNumber));

            writer.WriteLine("public override Builder MergeFrom(pb::CodedInputStream input) {");
            writer.WriteLine("  return MergeFrom(input, pb::ExtensionRegistry.Empty);");
            writer.WriteLine("}");
            writer.WriteLine();
            writer.WriteLine("public override Builder MergeFrom(pb::CodedInputStream input, pb::ExtensionRegistry extensionRegistry) {");
            writer.Indent();
            writer.WriteLine("pb::UnknownFieldSet.Builder unknownFields = null;");
            writer.WriteLine("while (true) {");
            writer.Indent();
            writer.WriteLine("uint tag = input.ReadTag();");
            writer.WriteLine("switch (tag) {");
            writer.Indent();
            writer.WriteLine("case 0: {"); // 0 signals EOF / limit reached
            writer.WriteLine("  if (unknownFields != null) {");
            writer.WriteLine("    this.UnknownFields = unknownFields.Build();");
            writer.WriteLine("  }");
            writer.WriteLine("  return this;");
            writer.WriteLine("}");
            writer.WriteLine("default: {");
            writer.WriteLine("  if (pb::WireFormat.IsEndGroupTag(tag)) {");
            writer.WriteLine("    if (unknownFields != null) {");
            writer.WriteLine("      this.UnknownFields = unknownFields.Build();");
            writer.WriteLine("    }");
            writer.WriteLine("    return this;");               // it's an endgroup tag
            writer.WriteLine("  }");
            writer.WriteLine("  if (unknownFields == null) {"); // First unknown field - create builder now
            writer.WriteLine("    unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields);");
            writer.WriteLine("  }");
            writer.WriteLine("  ParseUnknownField(input, unknownFields, extensionRegistry, tag);");
            writer.WriteLine("  break;");
            writer.WriteLine("}");
            foreach (FieldDescriptor field in sortedFields)
            {
                uint tag = WireFormat.MakeTag(field);
                writer.WriteLine("case {0}: {{", tag);
                writer.Indent();
                SourceGenerators.CreateFieldGenerator(field).GenerateParsingCode(writer);
                writer.WriteLine("break;");
                writer.Outdent();
                writer.WriteLine("}");
            }
            writer.Outdent();
            writer.WriteLine("}");
            writer.Outdent();
            writer.WriteLine("}");
            writer.Outdent();
            writer.WriteLine("}");
            writer.WriteLine();
        }
示例#19
0
        static IEnumerable <TableRow> CreateTableRows(string descriptorFile)
        {
            // We need to load the descriptor file with an extension registry containing the cloud_event_type extension.
            var fieldCodec         = FieldCodec.ForString(WireFormat.MakeTag(ExtensionField, WireFormat.WireType.LengthDelimited), "");
            var eventTypeExtension = new Extension <MessageOptions, string>(ExtensionField, fieldCodec);
            var extensionRegistry  = new ExtensionRegistry {
                eventTypeExtension
            };

            var bytes         = File.ReadAllBytes(descriptorFile);
            var descriptorSet = FileDescriptorSet.Parser.WithExtensionRegistry(extensionRegistry).ParseFrom(bytes);

            // For every file in the descriptor set, we check for messages with the cloud_event_type extension.
            // We gather all the
            foreach (var protoFile in descriptorSet.File)
            {
                // We currently assume there's only a single proto file per package that has cloud_event_type extensions,
                // conventionally events.proto. If that changes, we'll end up with multiple rows in the event
                // registry for a single package, one per file - at which point we'd need to keep a dictionary of
                // rows based on the package.
                var package = protoFile.Package;

                // Speculatively create a row in which to store any event types and data message names we find.
                var row = new TableRow(package);
                foreach (var message in protoFile.MessageType)
                {
                    // We only care about messages that have the cloud_event_type extension.
                    var eventType = message.Options?.GetExtension(eventTypeExtension);
                    if (string.IsNullOrWhiteSpace(eventType))
                    {
                        continue;
                    }

                    // Remember the event type specified in this message.
                    row.EventTypes.Add(eventType);

                    // Find the "data" field within the message, if there is one.
                    var dataFieldType = message.Field.FirstOrDefault(f => f.Name == "data")?.TypeName;
                    if (dataFieldType is string)
                    {
                        // Add the data message to the row.
                        // For the sake of making the table simple, we'll remove any package names etc,
                        // just leaving whatever comes after the final period.
                        row.DataMessages.Add(dataFieldType.Split('.').Last());
                    }
                }

                // If this proto contained any messages with event types, yield the row in the iterator.
                // Otherwise, ignore it.
                if (row.EventTypes.Any())
                {
                    yield return(row);
                }
            }
        }
示例#20
0
        static ArrayMessage()
        {
            var codeGenerator = MessageBuilder.GetCodeGenerator <T>();

            if (codeGenerator == null)
            {
                codeGenerator = (ICodeGenerator <T>)Activator.CreateInstance(typeof(ObjectCodeGenerator <>).MakeGenericType(typeof(T)));
            }
            _Tag        = WireFormat.MakeTag(1, codeGenerator.WireType);
            _FieldCodec = codeGenerator.CreateFieldCodec(1);
        }
示例#21
0
        public void CalculateSize_VariableSizePacked()
        {
            var list = new RepeatedField <int> {
                1, 500, 1
            };
            var tag = WireFormat.MakeTag(1, WireFormat.WireType.LengthDelimited);

            // 1 byte for the tag, 1 byte for the length,
            // 1 byte for the first entry, 2 bytes for the second, 1 byte for the third
            Assert.AreEqual(6, list.CalculateSize(FieldCodec.ForInt32(tag)));
        }
示例#22
0
        /// <summary>
        /// Create FieldCodec for type <typeparamref name="T"/>.
        /// </summary>
        /// <param name="fieldNumber">Number of field.</param>
        /// <returns>Return FieldCodec&lt;<typeparamref name="T"/>&gt;</returns>
        public override FieldCodec <T> CreateFieldCodec(int fieldNumber)
        {
            var readerType  = typeof(FieldCodec).Assembly.GetType("Google.Protobuf.ValueReader`1").MakeGenericType(typeof(T));
            var writerType  = typeof(FieldCodec).Assembly.GetType("Google.Protobuf.ValueWriter`1").MakeGenericType(typeof(T));
            var constructor = typeof(FieldCodec <T>).GetConstructor(BindingFlags.NonPublic | BindingFlags.Instance, null, new Type[] { readerType, writerType, typeof(Func <T, int>), typeof(uint), typeof(T) }, null);

            return((FieldCodec <T>)constructor.Invoke(new object[] {
                Delegate.CreateDelegate(readerType, this, GetType().GetMethod("ReadValue", BindingFlags.NonPublic | BindingFlags.Instance)),
                Delegate.CreateDelegate(writerType, this, GetType().GetMethod("WriteValue", BindingFlags.NonPublic | BindingFlags.Instance)),
                (Func <T, int>)CalculateSize,
                WireFormat.MakeTag(fieldNumber, WireType),
                default(T)
            }));
        }
示例#23
0
        public static uint GetTagForFieldNumber(this object o, int fieldNumber)
        {
            // Support upto 63 fields first
            if (fieldNumber > 63)
            {
                throw  new Exception("Only upto 63 fields are supported.");
            }

            if (VarintTypes.Contains(o.GetType()))
            {
                return(WireFormat.MakeTag(fieldNumber, WireFormat.WireType.Varint));
            }

            return(WireFormat.MakeTag(fieldNumber, WireFormat.WireType.LengthDelimited));
        }
示例#24
0
        public void ByteString_Test()
        {
            var codeGenerator = new ByteStringCodeGenerator();
            var value         = ByteString.CopyFrom(new byte[] { 23, 142, 53, 231, 123 });
            var fieldCodec    = codeGenerator.CreateFieldCodec(1);
            var stream        = new MemoryStream();
            var output        = new CodedOutputStream(stream, true);

            fieldCodec.WriteTagAndValue(output, value);
            output.Flush();
            stream.Position = 0;
            var input = new CodedInputStream(stream);

            Assert.Equal(WireFormat.MakeTag(1, codeGenerator.WireType), input.ReadTag());
            Assert.Equal(value, fieldCodec.Read(input));
        }
示例#25
0
        public void DateTime_Test()
        {
            var codeGenerator = new DateTimeCodeGenerator();
            var value         = DateTime.Now;
            var fieldCodec    = codeGenerator.CreateFieldCodec(1);
            var stream        = new MemoryStream();
            var output        = new CodedOutputStream(stream, true);

            fieldCodec.WriteTagAndValue(output, value);
            output.Flush();
            stream.Position = 0;
            var input = new CodedInputStream(stream);

            Assert.Equal(WireFormat.MakeTag(1, codeGenerator.WireType), input.ReadTag());
            Assert.Equal(value.ToUniversalTime(), fieldCodec.Read(input).ToUniversalTime());
        }
示例#26
0
        public void Byte_Test()
        {
            var  codeGenerator = new ByteCodeGenerator();
            byte value         = 245;
            var  fieldCodec    = codeGenerator.CreateFieldCodec(1);
            var  stream        = new MemoryStream();
            var  output        = new CodedOutputStream(stream, true);

            fieldCodec.WriteTagAndValue(output, value);
            output.Flush();
            stream.Position = 0;
            var input = new CodedInputStream(stream);

            Assert.Equal(WireFormat.MakeTag(1, codeGenerator.WireType), input.ReadTag());
            Assert.Equal(value, fieldCodec.Read(input));
        }
示例#27
0
        /// <summary>
        /// Loads the specified descriptor set, and extracts CloudEvent information from it.
        /// </summary>
        private static List <CloudEventDataInfo> LoadCloudEventDataInfo(string file)
        {
            // Note: while it's slightly annoying to hard-code this, it's less annoying than loading the
            // descriptor set without extensions, finding the extension number, and then reloading it.
            const int extensionField    = 11716486;
            var       fieldCodec        = FieldCodec.ForString(WireFormat.MakeTag(extensionField, WireFormat.WireType.LengthDelimited), "");
            var       extension         = new Extension <MessageOptions, string>(extensionField, fieldCodec);
            var       extensionRegistry = new ExtensionRegistry {
                extension
            };

            var descriptorSetBytes = File.ReadAllBytes(file);
            var descriptorSet      = FileDescriptorSet.Parser.WithExtensionRegistry(extensionRegistry).ParseFrom(descriptorSetBytes);

            var typeToNamespace = (from protoFile in descriptorSet.File
                                   from message in protoFile.MessageType
                                   select(protoFile, message))
                                  .ToDictionary(pair => $"{pair.protoFile.Package}.{pair.message.Name}", pair => pair.protoFile.Options.CsharpNamespace);

            // ConcurrentDictionary has a convenient GetOrAdd method.
            ConcurrentDictionary <string, CloudEventDataInfo> infoByFqn = new ConcurrentDictionary <string, CloudEventDataInfo>();

            // Find every message in every file in the descriptor set, and check for the cloud_event_type extension.
            // If it has one, check for a field called "data" and take the type of that, then create a CloudEventDataInfo
            // that knows the C# namespace of the message, the message name, and the CloudEvent type.
            foreach (var protoFile in descriptorSet.File)
            {
                var package = protoFile.Package;
                foreach (var message in protoFile.MessageType)
                {
                    var eventType = message.Options?.GetExtension(extension);
                    if (string.IsNullOrWhiteSpace(eventType))
                    {
                        continue;
                    }
                    // We expect each CloudEvent message to have a data field, which is a message.
                    var dataFieldType = message.Field.Single(f => f.Name == "data").TypeName;
                    // Convert the type to a fully-qualified name
                    var fqn                 = dataFieldType.StartsWith(".") ? dataFieldType.Substring(1) : $"{package}.{dataFieldType}";
                    var messageName         = fqn.Split('.').Last();
                    CloudEventDataInfo info = infoByFqn.GetOrAdd(fqn, _ => new CloudEventDataInfo(messageName, typeToNamespace[fqn]));
                    info.CloudEventTypes.Add(eventType);
                }
            }
            return(infoByFqn.Values.ToList());
        }
示例#28
0
        public void UInt64_Test()
        {
            var   codeGenerator = new UInt64CodeGenerator();
            ulong value         = 12413451231241356;

            Assert.Equal(CodedOutputStream.ComputeUInt64Size(value), codeGenerator.CalculateSize(value));
            var fieldCodec = codeGenerator.CreateFieldCodec(1);
            var stream     = new MemoryStream();
            var output     = new CodedOutputStream(stream, true);

            fieldCodec.WriteTagAndValue(output, value);
            output.Flush();
            stream.Position = 0;
            var input = new CodedInputStream(stream);

            Assert.Equal(WireFormat.MakeTag(1, codeGenerator.WireType), input.ReadTag());
            Assert.Equal(value, fieldCodec.Read(input));
        }
示例#29
0
        public void MergeFrom(CodedInputStream input)
        {
            uint tag;

            while ((tag = input.ReadTag()) != 0)
            {
                if (tag == WireFormat.MakeTag(1, WireFormat.WireType.Varint))
                {
                    this.Id = input.ReadInt32();
                }
                else if (tag == WireFormat.MakeTag(2, WireFormat.WireType.LengthDelimited))
                {
                    this.Nome = input.ReadString();
                }
                else
                {
                    input.SkipLastField();
                }
            }
        }
示例#30
0
 public void GenerateSerializationCode(TextGenerator writer)
 {
     writer.WriteLine("if ({0}_.Count > 0) {{", Name);
     writer.Indent();
     if (Descriptor.IsPacked)
     {
         writer.WriteLine("output.WriteRawVarint32({0});", WireFormat.MakeTag(Descriptor));
         writer.WriteLine("output.WriteRawVarint32((uint) {0}MemoizedSerializedSize);", Name);
         writer.WriteLine("foreach (int element in {0}_) {{", Name);
         writer.WriteLine("  output.WriteEnumNoTag(element);");
         writer.WriteLine("}");
     }
     else
     {
         writer.WriteLine("foreach (int element in {0}_) {{", Name);
         writer.WriteLine("  output.WriteEnum({0}, element);", Number);
         writer.WriteLine("}");
     }
     writer.Outdent();
     writer.WriteLine("}");
 }