Commit c4d1d9df authored by csharptest's avatar csharptest Committed by rogerk

reintegration with tip

parents 2cf6e1b0 b6a14572
===============================================================================
Welcome to the C# port of Google Protocol Buffers, written by Jon Skeet
(skeet@pobox.com) based on the work of many talented people.
For more information about this port, visit its homepage:
http://protobuf-csharp-port.googlecode.com
For more information about Protocol Buffers in general, visit the project page
for the C++, Java and Python project:
http://protobuf.googlecode.com
===============================================================================
RELEASE NOTES - Version TBD
===============================================================================
(PENDING MERGE)
- Issue 20: Support for decorating classes [Serializable]
- Issue 22: Reusable Builder classes
- Issue 24: Support for using Json/Xml formats with ICodedInputStream
Features:
- Added option service_generator_type to control service generation with
NONE, GENERIC, INTERFACE, or IRPCDISPATCH
- Added interfaces IRpcDispatch and IRpcServerStub to provide for blocking
services and implementations.
- Added ProtoGen.exe command-line argument "--protoc_dir=" to specify the
location of protoc.exe.
- Extracted interfaces for ICodedInputStream and ICodedOutputStream to allow
custom implementation of writers with both speed and size optimizations.
- Addition of the "Google.ProtoBuffers.Serialization" assembly to support
reading and writing messages to/from XML, JSON, IDictionary<,> and others.
- Several performance related fixes and tweeks
- Issue 3: Add option to mark generated code with attribute
- Issue 21: Decorate fields with [deprecated=true] as [System.Obsolete]
Fixes:
- Issue 13: Message with Field same name as message causes uncompilable .cs
- Issue 16: Does not integrate well with other tooling
- Issue 19: Support for negative enum values
- Issue 26: AddRange in GeneratedBuilder iterates twice.
- Issue 27: Remove XML documentation output from test projects to clear
warnings/errors.
- Big-endian support for float, and double on Silverlight
- Packed and Unpacked parsing allow for all repeated, as per version 2.3
- Fix for leaving Builder a public ctor on internal classes for use with
generic "where T: new()" constraints.
Other:
- Reformatted all code and line-endings to C# defaults
- Reworking of performance benchmarks to produce reliable results, option /v2
===============================================================================
RELEASE NOTES - Version 2.3.0.277
===============================================================================
Features:
- Added cls_compliance option to generate attributes indicating
non-CLS-compliance.
- Added file_extension option to control the generated output file's extension.
- Added umbrella_namespace option to place the umbrella class into a nested
namespace to address issues with proto files having the same name as a
message it contains.
- Added output_directory option to set the output path for the source file(s).
- Added ignore_google_protobuf option to avoid generating code for includes
from the google.protobuf package.
- Added the LITE framework (Google.ProtoBuffersLite.dll) and the ability to
generate code with "option optimize_for = LITE_RUNTIME;".
- Added ability to invoke protoc.exe from within ProtoGen.exe.
- Upgraded to protoc.exe (2.3) compiler.
Fixes:
- Issue 9: Class cannot be static and sealed error
- Issue 12: default value for enumerate fields must be filled out
Other:
- Rewrite of build using MSBbuild instead of NAnt
- Moved to NUnit Version 2.2.8.0
- Changed to using secure .snk for releases
===============================================================================
RELEASE NOTES - Version 0.9.1
===============================================================================
Fixes:
- issue 10: Incorrect encoding of packed fields when serialized
===============================================================================
RELEASE NOTES - Version 0.9.0
===============================================================================
- Initial release
===============================================================================
\ No newline at end of file
......@@ -3,6 +3,7 @@
import "google/protobuf/csharp_options.proto";
option (google.protobuf.csharp_file_options).namespace = "Google.ProtocolBuffers.TestProtos";
option (google.protobuf.csharp_file_options).umbrella_classname = "UnitTestExtrasLiteProtoFile";
option (google.protobuf.csharp_file_options).add_serializable = true;
package protobuf_unittest_extra;
......
import "google/protobuf/csharp_options.proto";
option (google.protobuf.csharp_file_options).namespace = "Google.ProtocolBuffers.TestProtos";
option (google.protobuf.csharp_file_options).umbrella_classname = "UnitTestXmlSerializerTestProtoFile";
option (google.protobuf.csharp_file_options).add_serializable = true;
package protobuf_unittest_extra;
......@@ -12,8 +13,7 @@ enum EnumOptions {
THREE = 2;
}
message TestXmlChild
{
message TestXmlChild {
repeated EnumOptions options = 3;
optional bytes binary = 4;
}
......@@ -34,13 +34,12 @@ message TestXmlMessage {
optional bool valid = 5;
optional TestXmlChild child = 1;
repeated group Children = 401
{
repeated group Children = 401 {
repeated EnumOptions options = 3;
optional bytes binary = 4;
}
extensions 100 to 199;
extensions 100 to 199;
}
message TestXmlExtension {
......
......@@ -86,3 +86,47 @@ message NumberField {
optional int32 _01 = 1;
}
// Issue 28: Circular message dependencies result in null defaults for DefaultInstance
message MyMessageAReferenceB {
required MyMessageBReferenceA value = 1;
}
message MyMessageBReferenceA {
required MyMessageAReferenceB value = 1;
}
// issue 19 - negative enum values
enum NegativeEnum {
FiveBelow = -5;
MinusOne = -1;
Zero = 0;
}
message NegativeEnumMessage {
optional NegativeEnum value = 1;
repeated NegativeEnum values = 2;
repeated NegativeEnum packed_values = 3 [packed=true];
}
// Issue 21: http://code.google.com/p/protobuf-csharp-port/issues/detail?id=21
// Decorate fields with [deprecated=true] as [System.Obsolete]
message DeprecatedChild {
}
enum DeprecatedEnum {
one = 1;
}
message DeprecatedFieldsMessage {
optional int32 PrimitiveValue = 1 [deprecated = true];
repeated int32 PrimitiveArray = 2 [deprecated = true];
optional DeprecatedChild MessageValue = 3 [deprecated = true];
repeated DeprecatedChild MessageArray = 4 [deprecated = true];
optional DeprecatedEnum EnumValue = 5 [deprecated = true];
repeated DeprecatedEnum EnumArray = 6 [deprecated = true];
}
\ No newline at end of file
......@@ -39,6 +39,9 @@ message CSharpFileOptions {
// Generate attributes indicating non-CLS-compliance
optional bool cls_compliance = 8 [default = true];
// Generate messages/builders with the [Serializable] attribute
optional bool add_serializable = 9 [default = false];
// The extension that should be appended to the umbrella_classname when creating files.
optional string file_extension = 221 [default = ".cs"];
......
<NotepadPlus>
<!--
Defines syntax highlighting for Notepad++.
1. Install Notepad++ from http://notepad-plus-plus.org
2. Open Notepad++, from the View menu, select "User-Defined Dialog..."
3. Click the "Import..." button and select this file
4. Restart Notepad++
5. Open and edit any *.proto file
-->
<UserLang name="Proto Buffer" ext="proto">
<Settings>
<Global caseIgnored="no" />
<TreatAsSymbol comment="no" commentLine="yes" />
<Prefix words1="no" words2="no" words3="no" words4="yes" />
</Settings>
<KeywordLists>
<Keywords name="Delimiters">[00]00</Keywords>
<Keywords name="Folder+">{</Keywords>
<Keywords name="Folder-">}</Keywords>
<Keywords name="Operators">=</Keywords>
<Keywords name="Comment"> 1option 1package 1import 2; 0//</Keywords>
<Keywords name="Words1">message enum service extend</Keywords>
<Keywords name="Words2">required optional repeated extensions to rpc returns</Keywords>
<Keywords name="Words3">double float int32 int64 uint32 uint64 sint32 sint64 fixed32 fixed64 sfixed32 sfixed64 bool string bytes</Keywords>
<Keywords name="Words4"></Keywords>
</KeywordLists>
<Styles>
<WordsStyle name="DEFAULT" styleID="11" fgColor="000000" bgColor="FFFFFF" fontStyle="0" />
<WordsStyle name="FOLDEROPEN" styleID="12" fgColor="000000" bgColor="FFFFFF" fontStyle="1" />
<WordsStyle name="FOLDERCLOSE" styleID="13" fgColor="000000" bgColor="FFFFFF" fontStyle="1" />
<WordsStyle name="KEYWORD1" styleID="5" fgColor="0000FF" bgColor="FFFFFF" fontStyle="0" />
<WordsStyle name="KEYWORD2" styleID="6" fgColor="0080C0" bgColor="FFFFFF" fontStyle="0" />
<WordsStyle name="KEYWORD3" styleID="7" fgColor="0000FF" bgColor="FFFFFF" fontStyle="0" />
<WordsStyle name="KEYWORD4" styleID="8" fgColor="008040" bgColor="FFFFFF" fontStyle="0" />
<WordsStyle name="COMMENT" styleID="1" fgColor="008000" bgColor="FFFFFF" fontStyle="0" />
<WordsStyle name="COMMENT LINE" styleID="2" fgColor="949494" bgColor="FFFFFF" fontStyle="0" />
<WordsStyle name="NUMBER" styleID="4" fgColor="FF0000" bgColor="FFFFFF" fontStyle="0" />
<WordsStyle name="OPERATOR" styleID="10" fgColor="000000" bgColor="FFFFFF" fontStyle="0" />
<WordsStyle name="DELIMINER1" styleID="14" fgColor="800080" bgColor="FFFFFF" fontStyle="0" />
<WordsStyle name="DELIMINER2" styleID="15" fgColor="808080" bgColor="FFFFFF" fontStyle="0" />
<WordsStyle name="DELIMINER3" styleID="16" fgColor="000000" bgColor="FFFFFF" fontStyle="0" />
</Styles>
</UserLang>
</NotepadPlus>
Welcome to the C# port of Google Protocol Buffers, written by Jon Skeet
(skeet@pobox.com) based on the work of many talented people.
For more information about this port, visit its homepage:
http://protobuf-csharp-port.googlecode.com
For more information about Protocol Buffers in general, visit the
project page for the C++, Java and Python project:
http://protobuf.googlecode.com
Release 0.9.1
-------------
Fix to release 0.9:
- Include protos in binary download
- Fix issue 10: incorrect encoding of packed fields when serialized
size wasn't fetched first
Release 0.9
-----------
Due to popular demand, I have built a version of the binaries to put
on the web site. Currently these are set at assembly version 0.9,
and an assembly file version of 0.9. This should be seen as a mark
of the readiness of the release process more than the stability of
the code. As far as I'm aware, the code itself is perfectly fine: I
certainly have plans for more features particularly around making
code generation simpler, but you should feel confident about the
parsing and serialization of messages produced with this version of
the library. Of course, if you do find any problems, *please* report
them at the web site.
Currently the downloadable release is built with the snk file which
is in the open source library. I am considering having a privately
held key so that you can check that you're building against a
"blessed" release - feedback on this (and any other aspect of the
release process) is very welcome.
This diff is collapsed.
......@@ -52,7 +52,7 @@ namespace Google.ProtocolBuffers.ProtoGen
{
FileDescriptorProto first = new FileDescriptorProto.Builder {Name = "First"}.Build();
FileDescriptorProto second = new FileDescriptorProto.Builder {Name = "Second"}.Build();
FileDescriptorSet set = new FileDescriptorSet {FileList = {first, second}};
FileDescriptorSet set = new FileDescriptorSet.Builder { FileList = { first, second } }.Build();
IList<FileDescriptor> converted = Generator.ConvertDescriptors(CSharpFileOptions.DefaultInstance, set);
Assert.AreEqual(2, converted.Count);
......@@ -68,7 +68,7 @@ namespace Google.ProtocolBuffers.ProtoGen
FileDescriptorProto first =
new FileDescriptorProto.Builder {Name = "First", DependencyList = {"Second"}}.Build();
FileDescriptorProto second = new FileDescriptorProto.Builder {Name = "Second"}.Build();
FileDescriptorSet set = new FileDescriptorSet {FileList = {first, second}};
FileDescriptorSet set = new FileDescriptorSet.Builder { FileList = { first, second } }.Build();
IList<FileDescriptor> converted = Generator.ConvertDescriptors(CSharpFileOptions.DefaultInstance, set);
Assert.AreEqual(2, converted.Count);
Assert.AreEqual("First", converted[0].Name);
......@@ -84,7 +84,7 @@ namespace Google.ProtocolBuffers.ProtoGen
FileDescriptorProto first = new FileDescriptorProto.Builder {Name = "First"}.Build();
FileDescriptorProto second =
new FileDescriptorProto.Builder {Name = "Second", DependencyList = {"First"}}.Build();
FileDescriptorSet set = new FileDescriptorSet {FileList = {first, second}};
FileDescriptorSet set = new FileDescriptorSet.Builder { FileList = { first, second } }.Build();
IList<FileDescriptor> converted = Generator.ConvertDescriptors(CSharpFileOptions.DefaultInstance, set);
Assert.AreEqual(2, converted.Count);
Assert.AreEqual("First", converted[0].Name);
......@@ -101,7 +101,7 @@ namespace Google.ProtocolBuffers.ProtoGen
new FileDescriptorProto.Builder {Name = "First", DependencyList = {"Second"}}.Build();
FileDescriptorProto second =
new FileDescriptorProto.Builder {Name = "Second", DependencyList = {"First"}}.Build();
FileDescriptorSet set = new FileDescriptorSet {FileList = {first, second}};
FileDescriptorSet set = new FileDescriptorSet.Builder { FileList = { first, second } }.Build();
try
{
Generator.ConvertDescriptors(CSharpFileOptions.DefaultInstance, set);
......@@ -118,7 +118,7 @@ namespace Google.ProtocolBuffers.ProtoGen
{
FileDescriptorProto first =
new FileDescriptorProto.Builder {Name = "First", DependencyList = {"Second"}}.Build();
FileDescriptorSet set = new FileDescriptorSet {FileList = {first}};
FileDescriptorSet set = new FileDescriptorSet.Builder { FileList = { first } }.Build();
try
{
Generator.ConvertDescriptors(CSharpFileOptions.DefaultInstance, set);
......@@ -135,7 +135,7 @@ namespace Google.ProtocolBuffers.ProtoGen
{
FileDescriptorProto first =
new FileDescriptorProto.Builder {Name = "First", DependencyList = {"First"}}.Build();
FileDescriptorSet set = new FileDescriptorSet {FileList = {first}};
FileDescriptorSet set = new FileDescriptorSet.Builder { FileList = { first } }.Build();
try
{
Generator.ConvertDescriptors(CSharpFileOptions.DefaultInstance, set);
......
......@@ -49,10 +49,11 @@ namespace Google.ProtocolBuffers.ProtoGen
{
writer.WriteLine("private bool has{0};", PropertyName);
writer.WriteLine("private {0} {1}_ = {2};", TypeName, Name, DefaultValue);
AddDeprecatedFlag(writer);
writer.WriteLine("public bool Has{0} {{", PropertyName);
writer.WriteLine(" get {{ return has{0}; }}", PropertyName);
writer.WriteLine("}");
AddClsComplianceCheck(writer);
AddPublicMemberAttributes(writer);
writer.WriteLine("public {0} {1} {{", TypeName, PropertyName);
writer.WriteLine(" get {{ return {0}_; }}", Name);
writer.WriteLine("}");
......@@ -60,21 +61,25 @@ namespace Google.ProtocolBuffers.ProtoGen
public void GenerateBuilderMembers(TextGenerator writer)
{
AddDeprecatedFlag(writer);
writer.WriteLine("public bool Has{0} {{", PropertyName);
writer.WriteLine(" get {{ return result.has{0}; }}", PropertyName);
writer.WriteLine("}");
AddClsComplianceCheck(writer);
AddPublicMemberAttributes(writer);
writer.WriteLine("public {0} {1} {{", TypeName, PropertyName);
writer.WriteLine(" get {{ return result.{0}; }}", PropertyName);
writer.WriteLine(" set {{ Set{0}(value); }}", PropertyName);
writer.WriteLine("}");
AddClsComplianceCheck(writer);
AddPublicMemberAttributes(writer);
writer.WriteLine("public Builder Set{0}({1} value) {{", PropertyName, TypeName);
writer.WriteLine(" PrepareBuilder();");
writer.WriteLine(" result.has{0} = true;", PropertyName);
writer.WriteLine(" result.{0}_ = value;", Name);
writer.WriteLine(" return this;");
writer.WriteLine("}");
AddDeprecatedFlag(writer);
writer.WriteLine("public Builder Clear{0}() {{", PropertyName);
writer.WriteLine(" PrepareBuilder();");
writer.WriteLine(" result.has{0} = false;", PropertyName);
writer.WriteLine(" result.{0}_ = {1};", Name, DefaultValue);
writer.WriteLine(" return this;");
......
......@@ -251,6 +251,12 @@ namespace Google.ProtocolBuffers.ProtoGen
}
}
protected void AddPublicMemberAttributes(TextGenerator writer)
{
AddDeprecatedFlag(writer);
AddClsComplianceCheck(writer);
}
protected void AddClsComplianceCheck(TextGenerator writer)
{
if (!Descriptor.IsCLSCompliant && Descriptor.File.CSharpOptions.ClsCompliance)
......@@ -259,6 +265,19 @@ namespace Google.ProtocolBuffers.ProtoGen
}
}
protected bool IsObsolete { get { return Descriptor.Options.Deprecated; } }
/// <summary>
/// Writes [global::System.ObsoleteAttribute()] if the member is obsolete
/// </summary>
protected void AddDeprecatedFlag(TextGenerator writer)
{
if (IsObsolete)
{
writer.WriteLine("[global::System.ObsoleteAttribute()]");
}
}
/// <summary>
/// For encodings with fixed sizes, returns that size in bytes. Otherwise
/// returns -1. TODO(jonskeet): Make this less ugly.
......
......@@ -48,38 +48,48 @@ namespace Google.ProtocolBuffers.ProtoGen
public void GenerateMembers(TextGenerator writer)
{
writer.WriteLine("private bool has{0};", PropertyName);
writer.WriteLine("private {0} {1}_ = {2};", TypeName, Name, DefaultValue);
writer.WriteLine("private {0} {1}_;", TypeName, Name);
AddDeprecatedFlag(writer);
writer.WriteLine("public bool Has{0} {{", PropertyName);
writer.WriteLine(" get {{ return has{0}; }}", PropertyName);
writer.WriteLine("}");
AddDeprecatedFlag(writer);
writer.WriteLine("public {0} {1} {{", TypeName, PropertyName);
writer.WriteLine(" get {{ return {0}_; }}", Name);
writer.WriteLine(" get {{ return {0}_ ?? {1}; }}", Name, DefaultValue);
writer.WriteLine("}");
}
public void GenerateBuilderMembers(TextGenerator writer)
{
AddDeprecatedFlag(writer);
writer.WriteLine("public bool Has{0} {{", PropertyName);
writer.WriteLine(" get {{ return result.has{0}; }}", PropertyName);
writer.WriteLine("}");
AddDeprecatedFlag(writer);
writer.WriteLine("public {0} {1} {{", TypeName, PropertyName);
writer.WriteLine(" get {{ return result.{0}; }}", PropertyName);
writer.WriteLine(" set {{ Set{0}(value); }}", PropertyName);
writer.WriteLine("}");
AddDeprecatedFlag(writer);
writer.WriteLine("public Builder Set{0}({1} value) {{", PropertyName, TypeName);
AddNullCheck(writer);
writer.WriteLine(" PrepareBuilder();");
writer.WriteLine(" result.has{0} = true;", PropertyName);
writer.WriteLine(" result.{0}_ = value;", Name);
writer.WriteLine(" return this;");
writer.WriteLine("}");
AddDeprecatedFlag(writer);
writer.WriteLine("public Builder Set{0}({1}.Builder builderForValue) {{", PropertyName, TypeName);
AddNullCheck(writer, "builderForValue");
writer.WriteLine(" PrepareBuilder();");
writer.WriteLine(" result.has{0} = true;", PropertyName);
writer.WriteLine(" result.{0}_ = builderForValue.Build();", Name);
writer.WriteLine(" return this;");
writer.WriteLine("}");
AddDeprecatedFlag(writer);
writer.WriteLine("public Builder Merge{0}({1} value) {{", PropertyName, TypeName);
AddNullCheck(writer);
writer.WriteLine(" PrepareBuilder();");
writer.WriteLine(" if (result.has{0} &&", PropertyName);
writer.WriteLine(" result.{0}_ != {1}) {{", Name, DefaultValue);
writer.WriteLine(" result.{0}_ = {1}.CreateBuilder(result.{0}_).MergeFrom(value).BuildPartial();", Name,
......@@ -90,9 +100,11 @@ namespace Google.ProtocolBuffers.ProtoGen
writer.WriteLine(" result.has{0} = true;", PropertyName);
writer.WriteLine(" return this;");
writer.WriteLine("}");
AddDeprecatedFlag(writer);
writer.WriteLine("public Builder Clear{0}() {{", PropertyName);
writer.WriteLine(" PrepareBuilder();");
writer.WriteLine(" result.has{0} = false;", PropertyName);
writer.WriteLine(" result.{0}_ = {1};", Name, DefaultValue);
writer.WriteLine(" result.{0}_ = null;", Name);
writer.WriteLine(" return this;");
writer.WriteLine("}");
}
......
......@@ -168,6 +168,10 @@ namespace Google.ProtocolBuffers.ProtoGen
public void Generate(TextGenerator writer)
{
if (Descriptor.File.CSharpOptions.AddSerializable)
{
writer.WriteLine("[global::System.SerializableAttribute()]");
}
writer.WriteLine("[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]");
writer.WriteLine("[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]");
writer.WriteLine("[global::System.CodeDom.Compiler.GeneratedCodeAttribute(\"{0}\", \"{1}\")]",
......@@ -177,8 +181,9 @@ namespace Google.ProtocolBuffers.ProtoGen
Descriptor.Proto.ExtensionRangeCount > 0 ? "Extendable" : "Generated",
RuntimeSuffix);
writer.Indent();
writer.WriteLine("private {0}() {{ }}", ClassName);
// Must call BuildPartial() to make sure all lists are made read-only
writer.WriteLine("private static readonly {0} defaultInstance = new Builder().BuildPartial();", ClassName);
writer.WriteLine("private static readonly {0} defaultInstance = new {0}().MakeReadOnly();", ClassName);
if (OptimizeSpeed)
{
......@@ -199,7 +204,7 @@ namespace Google.ProtocolBuffers.ProtoGen
writer.WriteLine("}");
writer.WriteLine();
writer.WriteLine("public override {0} DefaultInstanceForType {{", ClassName);
writer.WriteLine(" get { return defaultInstance; }");
writer.WriteLine(" get { return DefaultInstance; }");
writer.WriteLine("}");
writer.WriteLine();
writer.WriteLine("protected override {0} ThisMessage {{", ClassName);
......@@ -547,13 +552,28 @@ namespace Google.ProtocolBuffers.ProtoGen
private void GenerateBuilder(TextGenerator writer)
{
writer.WriteLine("private {0} MakeReadOnly() {{", ClassName);
writer.Indent();
foreach (FieldDescriptor field in Descriptor.Fields)
{
CreateFieldGenerator(field).GenerateBuildingCode(writer);
}
writer.WriteLine("return this;");
writer.Outdent();
writer.WriteLine("}");
writer.WriteLine();
writer.WriteLine("public static Builder CreateBuilder() { return new Builder(); }");
writer.WriteLine("public override Builder ToBuilder() { return CreateBuilder(this); }");
writer.WriteLine("public override Builder CreateBuilderForType() { return new Builder(); }");
writer.WriteLine("public static Builder CreateBuilder({0} prototype) {{", ClassName);
writer.WriteLine(" return (Builder) new Builder().MergeFrom(prototype);");
writer.WriteLine(" return new Builder(prototype);");
writer.WriteLine("}");
writer.WriteLine();
if (Descriptor.File.CSharpOptions.AddSerializable)
{
writer.WriteLine("[global::System.SerializableAttribute()]");
}
writer.WriteLine("[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]");
writer.WriteLine("[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]");
writer.WriteLine("[global::System.CodeDom.Compiler.GeneratedCodeAttribute(\"{0}\", \"{1}\")]",
......@@ -582,21 +602,52 @@ namespace Google.ProtocolBuffers.ProtoGen
private void GenerateCommonBuilderMethods(TextGenerator writer)
{
writer.WriteLine("public Builder() {{}}", ClassAccessLevel);
//default constructor
writer.WriteLine("public Builder() {");
//Durring static initialization of message, DefaultInstance is expected to return null.
writer.WriteLine(" result = DefaultInstance;");
writer.WriteLine(" resultIsReadOnly = true;");
writer.WriteLine("}");
//clone constructor
writer.WriteLine("internal Builder({0} cloneFrom) {{", ClassName);
writer.WriteLine(" result = cloneFrom;");
writer.WriteLine(" resultIsReadOnly = true;");
writer.WriteLine("}");
writer.WriteLine();
writer.WriteLine("private bool resultIsReadOnly;");
writer.WriteLine("private {0} result;", ClassName);
writer.WriteLine();
writer.WriteLine("private {0} PrepareBuilder() {{", ClassName);
writer.WriteLine(" if (resultIsReadOnly) {");
writer.WriteLine(" {0} original = result;", ClassName);
writer.WriteLine(" result = new {0}();", ClassName);
writer.WriteLine(" resultIsReadOnly = false;");
writer.WriteLine(" MergeFrom(original);");
writer.WriteLine(" }");
writer.WriteLine(" return result;");
writer.WriteLine("}");
writer.WriteLine();
writer.WriteLine("{0} result = new {0}();", ClassName);
writer.WriteLine("public override bool IsInitialized {");
writer.WriteLine(" get { return result.IsInitialized; }");
writer.WriteLine("}");
writer.WriteLine();
writer.WriteLine("protected override {0} MessageBeingBuilt {{", ClassName);
writer.WriteLine(" get { return result; }");
writer.WriteLine(" get { return PrepareBuilder(); }");
writer.WriteLine("}");
writer.WriteLine();
//Not actually expecting that DefaultInstance would ever be null here; however, we will ensure it does not break
writer.WriteLine("public override Builder Clear() {");
writer.WriteLine(" result = new {0}();", ClassName);
writer.WriteLine(" result = DefaultInstance;", ClassName);
writer.WriteLine(" resultIsReadOnly = true;");
writer.WriteLine(" return this;");
writer.WriteLine("}");
writer.WriteLine();
writer.WriteLine("public override Builder Clone() {");
writer.WriteLine(" if (resultIsReadOnly) {");
writer.WriteLine(" return new Builder(result);");
writer.WriteLine(" } else {");
writer.WriteLine(" return new Builder().MergeFrom(result);");
writer.WriteLine(" }");
writer.WriteLine("}");
writer.WriteLine();
if (!UseLiteRuntime)
......@@ -613,17 +664,11 @@ namespace Google.ProtocolBuffers.ProtoGen
writer.WriteLine("public override {0} BuildPartial() {{", ClassName);
writer.Indent();
writer.WriteLine("if (result == null) {");
writer.WriteLine(
" throw new global::System.InvalidOperationException(\"build() has already been called on this Builder\");");
writer.WriteLine("if (resultIsReadOnly) {");
writer.WriteLine(" return result;");
writer.WriteLine("}");
foreach (FieldDescriptor field in Descriptor.Fields)
{
CreateFieldGenerator(field).GenerateBuildingCode(writer);
}
writer.WriteLine("{0} returnMe = result;", ClassName);
writer.WriteLine("result = null;");
writer.WriteLine("return returnMe;");
writer.WriteLine("resultIsReadOnly = true;");
writer.WriteLine("return result.MakeReadOnly();");
writer.Outdent();
writer.WriteLine("}");
writer.WriteLine();
......@@ -644,6 +689,7 @@ namespace Google.ProtocolBuffers.ProtoGen
// fields are set so we can skip the merge.
writer.Indent();
writer.WriteLine("if (other == {0}.DefaultInstance) return this;", FullClassName);
writer.WriteLine("PrepareBuilder();");
foreach (FieldDescriptor field in Descriptor.Fields)
{
CreateFieldGenerator(field).GenerateMergingCode(writer);
......@@ -676,6 +722,7 @@ namespace Google.ProtocolBuffers.ProtoGen
writer.WriteLine(
"public override Builder MergeFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) {");
writer.Indent();
writer.WriteLine("PrepareBuilder();");
if (!UseLiteRuntime)
{
writer.WriteLine("pb::UnknownFieldSet.Builder unknownFields = null;");
......
......@@ -50,10 +50,11 @@ namespace Google.ProtocolBuffers.ProtoGen
{
writer.WriteLine("private bool has{0};", PropertyName);
writer.WriteLine("private {0} {1}_{2};", TypeName, Name, HasDefaultValue ? " = " + DefaultValue : "");
AddDeprecatedFlag(writer);
writer.WriteLine("public bool Has{0} {{", PropertyName);
writer.WriteLine(" get {{ return has{0}; }}", PropertyName);
writer.WriteLine("}");
AddClsComplianceCheck(writer);
AddPublicMemberAttributes(writer);
writer.WriteLine("public {0} {1} {{", TypeName, PropertyName);
writer.WriteLine(" get {{ return {0}_; }}", Name);
writer.WriteLine("}");
......@@ -61,22 +62,26 @@ namespace Google.ProtocolBuffers.ProtoGen
public void GenerateBuilderMembers(TextGenerator writer)
{
AddDeprecatedFlag(writer);
writer.WriteLine("public bool Has{0} {{", PropertyName);
writer.WriteLine(" get {{ return result.has{0}; }}", PropertyName);
writer.WriteLine("}");
AddClsComplianceCheck(writer);
AddPublicMemberAttributes(writer);
writer.WriteLine("public {0} {1} {{", TypeName, PropertyName);
writer.WriteLine(" get {{ return result.{0}; }}", PropertyName);
writer.WriteLine(" set {{ Set{0}(value); }}", PropertyName);
writer.WriteLine("}");
AddClsComplianceCheck(writer);
AddPublicMemberAttributes(writer);
writer.WriteLine("public Builder Set{0}({1} value) {{", PropertyName, TypeName);
AddNullCheck(writer);
writer.WriteLine(" PrepareBuilder();");
writer.WriteLine(" result.has{0} = true;", PropertyName);
writer.WriteLine(" result.{0}_ = value;", Name);
writer.WriteLine(" return this;");
writer.WriteLine("}");
AddDeprecatedFlag(writer);
writer.WriteLine("public Builder Clear{0}() {{", PropertyName);
writer.WriteLine(" PrepareBuilder();");
writer.WriteLine(" result.has{0} = false;", PropertyName);
writer.WriteLine(" result.{0}_ = {1};", Name, DefaultValue);
writer.WriteLine(" return this;");
......
......@@ -52,15 +52,18 @@ namespace Google.ProtocolBuffers.ProtoGen
writer.WriteLine("private int {0}MemoizedSerializedSize;", Name);
}
writer.WriteLine("private pbc::PopsicleList<{0}> {1}_ = new pbc::PopsicleList<{0}>();", TypeName, Name);
AddDeprecatedFlag(writer);
writer.WriteLine("public scg::IList<{0}> {1}List {{", TypeName, PropertyName);
writer.WriteLine(" get {{ return pbc::Lists.AsReadOnly({0}_); }}", Name);
writer.WriteLine("}");
// TODO(jonskeet): Redundant API calls? Possibly - include for portability though. Maybe create an option.
AddDeprecatedFlag(writer);
writer.WriteLine("public int {0}Count {{", PropertyName);
writer.WriteLine(" get {{ return {0}_.Count; }}", Name);
writer.WriteLine("}");
AddDeprecatedFlag(writer);
writer.WriteLine("public {0} Get{1}(int index) {{", TypeName, PropertyName);
writer.WriteLine(" return {0}_[index];", Name);
writer.WriteLine("}");
......@@ -70,28 +73,39 @@ namespace Google.ProtocolBuffers.ProtoGen
{
// Note: We can return the original list here, because we make it unmodifiable when we build
// We return it via IPopsicleList so that collection initializers work more pleasantly.
AddDeprecatedFlag(writer);
writer.WriteLine("public pbc::IPopsicleList<{0}> {1}List {{", TypeName, PropertyName);
writer.WriteLine(" get {{ return result.{0}_; }}", Name);
writer.WriteLine(" get {{ return PrepareBuilder().{0}_; }}", Name);
writer.WriteLine("}");
AddDeprecatedFlag(writer);
writer.WriteLine("public int {0}Count {{", PropertyName);
writer.WriteLine(" get {{ return result.{0}Count; }}", PropertyName);
writer.WriteLine("}");
AddDeprecatedFlag(writer);
writer.WriteLine("public {0} Get{1}(int index) {{", TypeName, PropertyName);
writer.WriteLine(" return result.Get{0}(index);", PropertyName);
writer.WriteLine("}");
AddDeprecatedFlag(writer);
writer.WriteLine("public Builder Set{0}(int index, {1} value) {{", PropertyName, TypeName);
writer.WriteLine(" PrepareBuilder();");
writer.WriteLine(" result.{0}_[index] = value;", Name);
writer.WriteLine(" return this;");
writer.WriteLine("}");
AddDeprecatedFlag(writer);
writer.WriteLine("public Builder Add{0}({1} value) {{", PropertyName, TypeName);
writer.WriteLine(" PrepareBuilder();");
writer.WriteLine(" result.{0}_.Add(value);", Name, TypeName);
writer.WriteLine(" return this;");
writer.WriteLine("}");
AddDeprecatedFlag(writer);
writer.WriteLine("public Builder AddRange{0}(scg::IEnumerable<{1}> values) {{", PropertyName, TypeName);
writer.WriteLine(" base.AddRange(values, result.{0}_);", Name);
writer.WriteLine(" PrepareBuilder();");
writer.WriteLine(" result.{0}_.Add(values);", Name);
writer.WriteLine(" return this;");
writer.WriteLine("}");
AddDeprecatedFlag(writer);
writer.WriteLine("public Builder Clear{0}() {{", PropertyName);
writer.WriteLine(" PrepareBuilder();");
writer.WriteLine(" result.{0}_.Clear();", Name);
writer.WriteLine(" return this;");
writer.WriteLine("}");
......@@ -100,13 +114,13 @@ namespace Google.ProtocolBuffers.ProtoGen
public void GenerateMergingCode(TextGenerator writer)
{
writer.WriteLine("if (other.{0}_.Count != 0) {{", Name);
writer.WriteLine(" base.AddRange(other.{0}_, result.{0}_);", Name);
writer.WriteLine(" result.{0}_.Add(other.{0}_);", Name);
writer.WriteLine("}");
}
public void GenerateBuildingCode(TextGenerator writer)
{
writer.WriteLine("result.{0}_.MakeReadOnly();", Name);
writer.WriteLine("{0}_.MakeReadOnly();", Name);
}
public void GenerateParsingCode(TextGenerator writer)
......
......@@ -48,15 +48,18 @@ namespace Google.ProtocolBuffers.ProtoGen
public void GenerateMembers(TextGenerator writer)
{
writer.WriteLine("private pbc::PopsicleList<{0}> {1}_ = new pbc::PopsicleList<{0}>();", TypeName, Name);
AddDeprecatedFlag(writer);
writer.WriteLine("public scg::IList<{0}> {1}List {{", TypeName, PropertyName);
writer.WriteLine(" get {{ return {0}_; }}", Name);
writer.WriteLine("}");
// TODO(jonskeet): Redundant API calls? Possibly - include for portability though. Maybe create an option.
AddDeprecatedFlag(writer);
writer.WriteLine("public int {0}Count {{", PropertyName);
writer.WriteLine(" get {{ return {0}_.Count; }}", Name);
writer.WriteLine("}");
AddDeprecatedFlag(writer);
writer.WriteLine("public {0} Get{1}(int index) {{", TypeName, PropertyName);
writer.WriteLine(" return {0}_[index];", Name);
writer.WriteLine("}");
......@@ -66,42 +69,57 @@ namespace Google.ProtocolBuffers.ProtoGen
{
// Note: We can return the original list here, because we make it unmodifiable when we build
// We return it via IPopsicleList so that collection initializers work more pleasantly.
AddDeprecatedFlag(writer);
writer.WriteLine("public pbc::IPopsicleList<{0}> {1}List {{", TypeName, PropertyName);
writer.WriteLine(" get {{ return result.{0}_; }}", Name);
writer.WriteLine(" get {{ return PrepareBuilder().{0}_; }}", Name);
writer.WriteLine("}");
AddDeprecatedFlag(writer);
writer.WriteLine("public int {0}Count {{", PropertyName);
writer.WriteLine(" get {{ return result.{0}Count; }}", PropertyName);
writer.WriteLine("}");
AddDeprecatedFlag(writer);
writer.WriteLine("public {0} Get{1}(int index) {{", TypeName, PropertyName);
writer.WriteLine(" return result.Get{0}(index);", PropertyName);
writer.WriteLine("}");
AddDeprecatedFlag(writer);
writer.WriteLine("public Builder Set{0}(int index, {1} value) {{", PropertyName, TypeName);
AddNullCheck(writer);
writer.WriteLine(" PrepareBuilder();");
writer.WriteLine(" result.{0}_[index] = value;", Name);
writer.WriteLine(" return this;");
writer.WriteLine("}");
// Extra overload for builder (just on messages)
AddDeprecatedFlag(writer);
writer.WriteLine("public Builder Set{0}(int index, {1}.Builder builderForValue) {{", PropertyName, TypeName);
AddNullCheck(writer, "builderForValue");
writer.WriteLine(" PrepareBuilder();");
writer.WriteLine(" result.{0}_[index] = builderForValue.Build();", Name);
writer.WriteLine(" return this;");
writer.WriteLine("}");
AddDeprecatedFlag(writer);
writer.WriteLine("public Builder Add{0}({1} value) {{", PropertyName, TypeName);
AddNullCheck(writer);
writer.WriteLine(" PrepareBuilder();");
writer.WriteLine(" result.{0}_.Add(value);", Name, TypeName);
writer.WriteLine(" return this;");
writer.WriteLine("}");
// Extra overload for builder (just on messages)
AddDeprecatedFlag(writer);
writer.WriteLine("public Builder Add{0}({1}.Builder builderForValue) {{", PropertyName, TypeName);
AddNullCheck(writer, "builderForValue");
writer.WriteLine(" PrepareBuilder();");
writer.WriteLine(" result.{0}_.Add(builderForValue.Build());", Name);
writer.WriteLine(" return this;");
writer.WriteLine("}");
AddDeprecatedFlag(writer);
writer.WriteLine("public Builder AddRange{0}(scg::IEnumerable<{1}> values) {{", PropertyName, TypeName);
writer.WriteLine(" base.AddRange(values, result.{0}_);", Name);
writer.WriteLine(" PrepareBuilder();");
writer.WriteLine(" result.{0}_.Add(values);", Name);
writer.WriteLine(" return this;");
writer.WriteLine("}");
AddDeprecatedFlag(writer);
writer.WriteLine("public Builder Clear{0}() {{", PropertyName);
writer.WriteLine(" PrepareBuilder();");
writer.WriteLine(" result.{0}_.Clear();", Name);
writer.WriteLine(" return this;");
writer.WriteLine("}");
......@@ -110,13 +128,13 @@ namespace Google.ProtocolBuffers.ProtoGen
public void GenerateMergingCode(TextGenerator writer)
{
writer.WriteLine("if (other.{0}_.Count != 0) {{", Name);
writer.WriteLine(" base.AddRange(other.{0}_, result.{0}_);", Name);
writer.WriteLine(" result.{0}_.Add(other.{0}_);", Name);
writer.WriteLine("}");
}
public void GenerateBuildingCode(TextGenerator writer)
{
writer.WriteLine("result.{0}_.MakeReadOnly();", Name);
writer.WriteLine("{0}_.MakeReadOnly();", Name);
}
public void GenerateParsingCode(TextGenerator writer)
......
......@@ -52,17 +52,18 @@ namespace Google.ProtocolBuffers.ProtoGen
writer.WriteLine("private int {0}MemoizedSerializedSize;", Name);
}
writer.WriteLine("private pbc::PopsicleList<{0}> {1}_ = new pbc::PopsicleList<{0}>();", TypeName, Name);
AddClsComplianceCheck(writer);
AddPublicMemberAttributes(writer);
writer.WriteLine("public scg::IList<{0}> {1}List {{", TypeName, PropertyName);
writer.WriteLine(" get {{ return pbc::Lists.AsReadOnly({0}_); }}", Name);
writer.WriteLine("}");
// TODO(jonskeet): Redundant API calls? Possibly - include for portability though. Maybe create an option.
AddDeprecatedFlag(writer);
writer.WriteLine("public int {0}Count {{", PropertyName);
writer.WriteLine(" get {{ return {0}_.Count; }}", Name);
writer.WriteLine("}");
AddClsComplianceCheck(writer);
AddPublicMemberAttributes(writer);
writer.WriteLine("public {0} Get{1}(int index) {{", TypeName, PropertyName);
writer.WriteLine(" return {0}_[index];", Name);
writer.WriteLine("}");
......@@ -72,35 +73,41 @@ namespace Google.ProtocolBuffers.ProtoGen
{
// Note: We can return the original list here, because we make it unmodifiable when we build
// We return it via IPopsicleList so that collection initializers work more pleasantly.
AddClsComplianceCheck(writer);
AddPublicMemberAttributes(writer);
writer.WriteLine("public pbc::IPopsicleList<{0}> {1}List {{", TypeName, PropertyName);
writer.WriteLine(" get {{ return result.{0}_; }}", Name);
writer.WriteLine(" get {{ return PrepareBuilder().{0}_; }}", Name);
writer.WriteLine("}");
AddDeprecatedFlag(writer);
writer.WriteLine("public int {0}Count {{", PropertyName);
writer.WriteLine(" get {{ return result.{0}Count; }}", PropertyName);
writer.WriteLine("}");
AddClsComplianceCheck(writer);
AddPublicMemberAttributes(writer);
writer.WriteLine("public {0} Get{1}(int index) {{", TypeName, PropertyName);
writer.WriteLine(" return result.Get{0}(index);", PropertyName);
writer.WriteLine("}");
AddClsComplianceCheck(writer);
AddPublicMemberAttributes(writer);
writer.WriteLine("public Builder Set{0}(int index, {1} value) {{", PropertyName, TypeName);
AddNullCheck(writer);
writer.WriteLine(" PrepareBuilder();");
writer.WriteLine(" result.{0}_[index] = value;", Name);
writer.WriteLine(" return this;");
writer.WriteLine("}");
AddClsComplianceCheck(writer);
AddPublicMemberAttributes(writer);
writer.WriteLine("public Builder Add{0}({1} value) {{", PropertyName, TypeName);
AddNullCheck(writer);
writer.WriteLine(" PrepareBuilder();");
writer.WriteLine(" result.{0}_.Add(value);", Name, TypeName);
writer.WriteLine(" return this;");
writer.WriteLine("}");
AddClsComplianceCheck(writer);
AddPublicMemberAttributes(writer);
writer.WriteLine("public Builder AddRange{0}(scg::IEnumerable<{1}> values) {{", PropertyName, TypeName);
writer.WriteLine(" base.AddRange(values, result.{0}_);", Name);
writer.WriteLine(" PrepareBuilder();");
writer.WriteLine(" result.{0}_.Add(values);", Name);
writer.WriteLine(" return this;");
writer.WriteLine("}");
AddDeprecatedFlag(writer);
writer.WriteLine("public Builder Clear{0}() {{", PropertyName);
writer.WriteLine(" PrepareBuilder();");
writer.WriteLine(" result.{0}_.Clear();", Name);
writer.WriteLine(" return this;");
writer.WriteLine("}");
......@@ -109,13 +116,13 @@ namespace Google.ProtocolBuffers.ProtoGen
public void GenerateMergingCode(TextGenerator writer)
{
writer.WriteLine("if (other.{0}_.Count != 0) {{", Name);
writer.WriteLine(" base.AddRange(other.{0}_, result.{0}_);", Name);
writer.WriteLine(" result.{0}_.Add(other.{0}_);", Name);
writer.WriteLine("}");
}
public void GenerateBuildingCode(TextGenerator writer)
{
writer.WriteLine("result.{0}_.MakeReadOnly();", Name);
writer.WriteLine("{0}_.MakeReadOnly();", Name);
}
public void GenerateParsingCode(TextGenerator writer)
......
......@@ -139,7 +139,7 @@ namespace Google.ProtocolBuffers.ProtoGen
private void WriteIntroduction(TextGenerator writer)
{
writer.WriteLine("// Generated by {0}. DO NOT EDIT!", this.GetType().Assembly.FullName);
writer.WriteLine("#pragma warning disable 1591");
writer.WriteLine("#pragma warning disable 1591, 0612");
writer.WriteLine("#region Designer generated code");
writer.WriteLine();
......
......@@ -35,6 +35,7 @@
#endregion
using System;
using System.Collections.Generic;
using System.IO;
using Google.ProtocolBuffers.TestProtos;
using NUnit.Framework;
......@@ -532,5 +533,77 @@ namespace Google.ProtocolBuffers
return base.Read(buffer, offset, Math.Min(count, blockSize));
}
}
enum TestNegEnum { None = 0, Value = -2 }
[Test]
public void TestNegativeEnum()
{
byte[] bytes = new byte[10] { 0xFE, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01 };
CodedInputStream input = CodedInputStream.CreateInstance(bytes);
object unk;
TestNegEnum val = TestNegEnum.None;
Assert.IsTrue(input.ReadEnum(ref val, out unk));
Assert.IsTrue(input.IsAtEnd);
Assert.AreEqual(TestNegEnum.Value, val);
}
[Test]
public void TestNegativeEnumPackedArray()
{
int arraySize = 1 + (10 * 5);
int msgSize = 1 + 1 + arraySize;
byte[] bytes = new byte[msgSize];
CodedOutputStream output = CodedOutputStream.CreateInstance(bytes);
output.WritePackedInt32Array(8, "", arraySize, new int[] { 0, -1, -2, -3, -4, -5 });
Assert.AreEqual(0, output.SpaceLeft);
CodedInputStream input = CodedInputStream.CreateInstance(bytes);
uint tag;
string name;
Assert.IsTrue(input.ReadTag(out tag, out name));
List<TestNegEnum> values = new List<TestNegEnum>();
ICollection<object> unk;
input.ReadEnumArray(tag, name, values, out unk);
Assert.AreEqual(2, values.Count);
Assert.AreEqual(TestNegEnum.None, values[0]);
Assert.AreEqual(TestNegEnum.Value, values[1]);
Assert.IsNotNull(unk);
Assert.AreEqual(4, unk.Count);
}
[Test]
public void TestNegativeEnumArray()
{
int arraySize = 1 + 1 + (11 * 5);
int msgSize = arraySize;
byte[] bytes = new byte[msgSize];
CodedOutputStream output = CodedOutputStream.CreateInstance(bytes);
output.WriteInt32Array(8, "", new int[] { 0, -1, -2, -3, -4, -5 });
Assert.AreEqual(0, output.SpaceLeft);
CodedInputStream input = CodedInputStream.CreateInstance(bytes);
uint tag;
string name;
Assert.IsTrue(input.ReadTag(out tag, out name));
List<TestNegEnum> values = new List<TestNegEnum>();
ICollection<object> unk;
input.ReadEnumArray(tag, name, values, out unk);
Assert.AreEqual(2, values.Count);
Assert.AreEqual(TestNegEnum.None, values[0]);
Assert.AreEqual(TestNegEnum.Value, values[1]);
Assert.IsNotNull(unk);
Assert.AreEqual(4, unk.Count);
}
}
}
\ No newline at end of file
......@@ -34,6 +34,8 @@
#endregion
using System;
using System.Collections.Generic;
using System.IO;
using Google.ProtocolBuffers.TestProtos;
using NUnit.Framework;
......@@ -288,5 +290,82 @@ namespace Google.ProtocolBuffers
Assert.AreEqual(-75123905439571256L,
CodedInputStream.DecodeZigZag64(CodedOutputStream.EncodeZigZag64(-75123905439571256L)));
}
[Test]
public void TestNegativeEnumNoTag()
{
Assert.AreEqual(10, CodedOutputStream.ComputeInt32SizeNoTag(-2));
Assert.AreEqual(10, CodedOutputStream.ComputeEnumSizeNoTag(-2));
byte[] bytes = new byte[10];
CodedOutputStream output = CodedOutputStream.CreateInstance(bytes);
output.WriteEnumNoTag(-2);
Assert.AreEqual(0, output.SpaceLeft);
Assert.AreEqual("FE-FF-FF-FF-FF-FF-FF-FF-FF-01", BitConverter.ToString(bytes));
}
[Test]
public void TestNegativeEnumWithTag()
{
Assert.AreEqual(11, CodedOutputStream.ComputeInt32Size(8, -2));
Assert.AreEqual(11, CodedOutputStream.ComputeEnumSize(8, -2));
byte[] bytes = new byte[11];
CodedOutputStream output = CodedOutputStream.CreateInstance(bytes);
output.WriteEnum(8, "", -2, -2);
Assert.AreEqual(0, output.SpaceLeft);
//fyi, 0x40 == 0x08 << 3 + 0, field num + wire format shift
Assert.AreEqual("40-FE-FF-FF-FF-FF-FF-FF-FF-FF-01", BitConverter.ToString(bytes));
}
[Test]
public void TestNegativeEnumArrayPacked()
{
int arraySize = 1 + (10 * 5);
int msgSize = 1 + 1 + arraySize;
byte[] bytes = new byte[msgSize];
CodedOutputStream output = CodedOutputStream.CreateInstance(bytes);
output.WritePackedEnumArray(8, "", arraySize, new int[] { 0, -1, -2, -3, -4, -5 });
Assert.AreEqual(0, output.SpaceLeft);
CodedInputStream input = CodedInputStream.CreateInstance(bytes);
uint tag;
string name;
Assert.IsTrue(input.ReadTag(out tag, out name));
List<int> values = new List<int>();
input.ReadInt32Array(tag, name, values);
Assert.AreEqual(6, values.Count);
for (int i = 0; i > -6; i--)
Assert.AreEqual(i, values[Math.Abs(i)]);
}
[Test]
public void TestNegativeEnumArray()
{
int arraySize = 1 + 1 + (11 * 5);
int msgSize = arraySize;
byte[] bytes = new byte[msgSize];
CodedOutputStream output = CodedOutputStream.CreateInstance(bytes);
output.WriteEnumArray(8, "", new int[] { 0, -1, -2, -3, -4, -5 });
Assert.AreEqual(0, output.SpaceLeft);
CodedInputStream input = CodedInputStream.CreateInstance(bytes);
uint tag;
string name;
Assert.IsTrue(input.ReadTag(out tag, out name));
List<int> values = new List<int>();
input.ReadInt32Array(tag, name, values);
Assert.AreEqual(6, values.Count);
for (int i = 0; i > -6; i--)
Assert.AreEqual(i, values[Math.Abs(i)]);
}
}
}
\ No newline at end of file
......@@ -35,6 +35,7 @@
#endregion
using System;
using System.Collections.Generic;
using NUnit.Framework;
internal delegate void Action();
......@@ -94,6 +95,64 @@ namespace Google.ProtocolBuffers.Collections
Assert.IsFalse(list.IsReadOnly);
}
[Test]
public void DoesNotAddNullEnumerable()
{
PopsicleList<string> list = new PopsicleList<string>();
try
{
list.Add((IEnumerable<string>)null);
}
catch (ArgumentNullException)
{ return; }
Assert.Fail("List should not allow nulls.");
}
[Test]
public void DoesNotAddRangeWithNull()
{
PopsicleList<string> list = new PopsicleList<string>();
try
{
list.Add(new[] { "a", "b", null });
}
catch (ArgumentNullException)
{ return; }
Assert.Fail("List should not allow nulls.");
}
[Test]
public void DoesNotAddNull()
{
PopsicleList<string> list = new PopsicleList<string>();
try
{
list.Add((string)null);
}
catch (ArgumentNullException)
{ return; }
Assert.Fail("List should not allow nulls.");
}
[Test]
public void DoesNotSetNull()
{
PopsicleList<string> list = new PopsicleList<string>();
list.Add("a");
try
{
list[0] = null;
}
catch (ArgumentNullException)
{ return; }
Assert.Fail("List should not allow nulls.");
}
private static void AssertNotSupported(Action action)
{
try
......
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text;
using NUnit.Framework;
using UnitTest.Issues.TestProtos;
namespace Google.ProtocolBuffers
{
[TestFixture]
public class DeprecatedMemberTest
{
private static void AssertIsDeprecated(ICustomAttributeProvider member)
{
Assert.IsNotNull(member);
Assert.IsTrue(member.IsDefined(typeof(ObsoleteAttribute), false), "Member not obsolete: " + member);
}
[Test]
public void TestDepreatedPrimitiveValue()
{
AssertIsDeprecated(typeof(DeprecatedFieldsMessage).GetProperty("HasPrimitiveValue"));
AssertIsDeprecated(typeof(DeprecatedFieldsMessage).GetProperty("PrimitiveValue"));
AssertIsDeprecated(typeof(DeprecatedFieldsMessage.Builder).GetProperty("HasPrimitiveValue"));
AssertIsDeprecated(typeof(DeprecatedFieldsMessage.Builder).GetProperty("PrimitiveValue"));
AssertIsDeprecated(typeof(DeprecatedFieldsMessage.Builder).GetMethod("ClearPrimitiveValue"));
AssertIsDeprecated(typeof(DeprecatedFieldsMessage.Builder).GetMethod("SetPrimitiveValue"));
}
[Test]
public void TestDepreatedPrimitiveArray()
{
AssertIsDeprecated(typeof(DeprecatedFieldsMessage).GetProperty("PrimitiveArrayList"));
AssertIsDeprecated(typeof(DeprecatedFieldsMessage).GetProperty("PrimitiveArrayCount"));
AssertIsDeprecated(typeof(DeprecatedFieldsMessage).GetMethod("GetPrimitiveArray"));
AssertIsDeprecated(typeof(DeprecatedFieldsMessage.Builder).GetProperty("PrimitiveArrayList"));
AssertIsDeprecated(typeof(DeprecatedFieldsMessage.Builder).GetProperty("PrimitiveArrayCount"));
AssertIsDeprecated(typeof(DeprecatedFieldsMessage.Builder).GetMethod("GetPrimitiveArray"));
AssertIsDeprecated(typeof(DeprecatedFieldsMessage.Builder).GetMethod("SetPrimitiveArray"));
AssertIsDeprecated(typeof(DeprecatedFieldsMessage.Builder).GetMethod("AddPrimitiveArray"));
AssertIsDeprecated(typeof(DeprecatedFieldsMessage.Builder).GetMethod("AddRangePrimitiveArray"));
AssertIsDeprecated(typeof(DeprecatedFieldsMessage.Builder).GetMethod("ClearPrimitiveArray"));
}
[Test]
public void TestDepreatedMessageValue()
{
AssertIsDeprecated(typeof(DeprecatedFieldsMessage).GetProperty("HasMessageValue"));
AssertIsDeprecated(typeof(DeprecatedFieldsMessage).GetProperty("MessageValue"));
AssertIsDeprecated(typeof(DeprecatedFieldsMessage.Builder).GetProperty("HasMessageValue"));
AssertIsDeprecated(typeof(DeprecatedFieldsMessage.Builder).GetProperty("MessageValue"));
AssertIsDeprecated(typeof(DeprecatedFieldsMessage.Builder).GetMethod("MergeMessageValue"));
AssertIsDeprecated(typeof(DeprecatedFieldsMessage.Builder).GetMethod("ClearMessageValue"));
AssertIsDeprecated(typeof(DeprecatedFieldsMessage.Builder).GetMethod("SetMessageValue", new[] { typeof(DeprecatedChild) }));
AssertIsDeprecated(typeof(DeprecatedFieldsMessage.Builder).GetMethod("SetMessageValue", new[] { typeof(DeprecatedChild.Builder) }));
}
[Test]
public void TestDepreatedMessageArray()
{
AssertIsDeprecated(typeof(DeprecatedFieldsMessage).GetProperty("MessageArrayList"));
AssertIsDeprecated(typeof(DeprecatedFieldsMessage).GetProperty("MessageArrayCount"));
AssertIsDeprecated(typeof(DeprecatedFieldsMessage).GetMethod("GetMessageArray"));
AssertIsDeprecated(typeof(DeprecatedFieldsMessage.Builder).GetProperty("MessageArrayList"));
AssertIsDeprecated(typeof(DeprecatedFieldsMessage.Builder).GetProperty("MessageArrayCount"));
AssertIsDeprecated(typeof(DeprecatedFieldsMessage.Builder).GetMethod("GetMessageArray"));
AssertIsDeprecated(typeof(DeprecatedFieldsMessage.Builder).GetMethod("SetMessageArray", new[] { typeof(int), typeof(DeprecatedChild) }));
AssertIsDeprecated(typeof(DeprecatedFieldsMessage.Builder).GetMethod("SetMessageArray", new[] { typeof(int), typeof(DeprecatedChild.Builder) }));
AssertIsDeprecated(typeof(DeprecatedFieldsMessage.Builder).GetMethod("AddMessageArray", new[] { typeof(DeprecatedChild) }));
AssertIsDeprecated(typeof(DeprecatedFieldsMessage.Builder).GetMethod("AddMessageArray", new[] { typeof(DeprecatedChild.Builder) }));
AssertIsDeprecated(typeof(DeprecatedFieldsMessage.Builder).GetMethod("AddRangeMessageArray"));
AssertIsDeprecated(typeof(DeprecatedFieldsMessage.Builder).GetMethod("ClearMessageArray"));
}
[Test]
public void TestDepreatedEnumValue()
{
AssertIsDeprecated(typeof(DeprecatedFieldsMessage).GetProperty("HasEnumValue"));
AssertIsDeprecated(typeof(DeprecatedFieldsMessage).GetProperty("EnumValue"));
AssertIsDeprecated(typeof(DeprecatedFieldsMessage.Builder).GetProperty("HasEnumValue"));
AssertIsDeprecated(typeof(DeprecatedFieldsMessage.Builder).GetProperty("EnumValue"));
AssertIsDeprecated(typeof(DeprecatedFieldsMessage.Builder).GetMethod("ClearEnumValue"));
AssertIsDeprecated(typeof(DeprecatedFieldsMessage.Builder).GetMethod("SetEnumValue"));
}
[Test]
public void TestDepreatedEnumArray()
{
AssertIsDeprecated(typeof(DeprecatedFieldsMessage).GetProperty("EnumArrayList"));
AssertIsDeprecated(typeof(DeprecatedFieldsMessage).GetProperty("EnumArrayCount"));
AssertIsDeprecated(typeof(DeprecatedFieldsMessage).GetMethod("GetEnumArray"));
AssertIsDeprecated(typeof(DeprecatedFieldsMessage.Builder).GetProperty("EnumArrayList"));
AssertIsDeprecated(typeof(DeprecatedFieldsMessage.Builder).GetProperty("EnumArrayCount"));
AssertIsDeprecated(typeof(DeprecatedFieldsMessage.Builder).GetMethod("GetEnumArray"));
AssertIsDeprecated(typeof(DeprecatedFieldsMessage.Builder).GetMethod("SetEnumArray"));
AssertIsDeprecated(typeof(DeprecatedFieldsMessage.Builder).GetMethod("AddEnumArray"));
AssertIsDeprecated(typeof(DeprecatedFieldsMessage.Builder).GetMethod("AddRangeEnumArray"));
AssertIsDeprecated(typeof(DeprecatedFieldsMessage.Builder).GetMethod("ClearEnumArray"));
}
}
}
using System;
using System.Collections.Generic;
using System.Text;
using Google.ProtocolBuffers.TestProtos;
using NUnit.Framework;
namespace Google.ProtocolBuffers
{
[TestFixture]
public class GeneratedBuilderTest
{
class OneTimeEnumerator<T> : IEnumerable<T>
{
readonly T _item;
bool _enumerated;
public OneTimeEnumerator(T item)
{
_item = item;
}
public IEnumerator<T> GetEnumerator()
{
Assert.IsFalse(_enumerated, "The collection {0} has already been enumerated", GetType());
_enumerated = true;
yield return _item;
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{ return GetEnumerator(); }
}
[Test]
public void DoesNotEnumerateTwiceForMessageList()
{
TestAllTypes.Builder b = new TestAllTypes.Builder();
b.AddRangeRepeatedForeignMessage(
new OneTimeEnumerator<ForeignMessage>(
ForeignMessage.DefaultInstance));
}
[Test]
public void DoesNotEnumerateTwiceForPrimitiveList()
{
TestAllTypes.Builder b = new TestAllTypes.Builder();
b.AddRangeRepeatedInt32(new OneTimeEnumerator<int>(1));
}
[Test]
public void DoesNotEnumerateTwiceForStringList()
{
TestAllTypes.Builder b = new TestAllTypes.Builder();
b.AddRangeRepeatedString(new OneTimeEnumerator<string>("test"));
}
[Test]
public void DoesNotEnumerateTwiceForEnumList()
{
TestAllTypes.Builder b = new TestAllTypes.Builder();
b.AddRangeRepeatedForeignEnum(new OneTimeEnumerator<ForeignEnum>(ForeignEnum.FOREIGN_BAR));
}
private static void AssertThrows<T>(System.Threading.ThreadStart method) where T : Exception
{
try
{
method();
}
catch (Exception error)
{
if (error is T)
return;
throw;
}
Assert.Fail("Expected exception of type " + typeof(T));
}
[Test]
public void DoesNotAddNullToMessageListByAddRange()
{
TestAllTypes.Builder b = new TestAllTypes.Builder();
AssertThrows<ArgumentNullException>(
() => b.AddRangeRepeatedForeignMessage(new ForeignMessage[] { null })
);
}
[Test]
public void DoesNotAddNullToMessageListByAdd()
{
TestAllTypes.Builder b = new TestAllTypes.Builder();
AssertThrows<ArgumentNullException>(
() => b.AddRepeatedForeignMessage((ForeignMessage)null)
);
}
[Test]
public void DoesNotAddNullToMessageListBySet()
{
TestAllTypes.Builder b = new TestAllTypes.Builder();
b.AddRepeatedForeignMessage(ForeignMessage.DefaultInstance);
AssertThrows<ArgumentNullException>(
() => b.SetRepeatedForeignMessage(0, (ForeignMessage)null)
);
}
[Test]
public void DoesNotAddNullToStringListByAddRange()
{
TestAllTypes.Builder b = new TestAllTypes.Builder();
AssertThrows<ArgumentNullException>(
() => b.AddRangeRepeatedString(new String[] { null })
);
}
[Test]
public void DoesNotAddNullToStringListByAdd()
{
TestAllTypes.Builder b = new TestAllTypes.Builder();
AssertThrows<ArgumentNullException>(
() => b.AddRepeatedString(null)
);
}
[Test]
public void DoesNotAddNullToStringListBySet()
{
TestAllTypes.Builder b = new TestAllTypes.Builder();
b.AddRepeatedString("one");
AssertThrows<ArgumentNullException>(
() => b.SetRepeatedString(0, null)
);
}
}
}
......@@ -111,22 +111,6 @@ namespace Google.ProtocolBuffers
}
}
[Test]
public void DoubleBuildError()
{
TestAllTypes.Builder builder = new TestAllTypes.Builder();
builder.Build();
try
{
builder.Build();
Assert.Fail("Should have thrown exception.");
}
catch (InvalidOperationException)
{
// Success.
}
}
[Test]
public void DefaultInstance()
{
......
......@@ -45,9 +45,7 @@
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
<DocumentationFile>bin\Debug\Google.ProtocolBuffers.Test.XML</DocumentationFile>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<NoWarn>1591</NoWarn>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
......@@ -57,9 +55,7 @@
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
<DocumentationFile>bin\Release\Google.ProtocolBuffers.Test.XML</DocumentationFile>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<NoWarn>1591</NoWarn>
</PropertyGroup>
<ItemGroup>
<Reference Include="nunit.framework, Version=2.2.8.0, Culture=neutral, PublicKeyToken=96d09a1eb7f44a77">
......@@ -94,10 +90,12 @@
<Compile Include="Compatibility\XmlCompatibilityTests.cs" />
<Compile Include="TestReaderForUrlEncoded.cs" />
<Compile Include="CSharpOptionsTest.cs" />
<Compile Include="DeprecatedMemberTest.cs" />
<Compile Include="DescriptorsTest.cs" />
<Compile Include="Descriptors\MessageDescriptorTest.cs" />
<Compile Include="DynamicMessageTest.cs" />
<Compile Include="ExtendableMessageTest.cs" />
<Compile Include="GeneratedBuilderTest.cs" />
<Compile Include="GeneratedMessageTest.cs" />
<Compile Include="MessageStreamIteratorTest.cs" />
<Compile Include="MessageStreamWriterTest.cs" />
......@@ -106,7 +104,10 @@
<Compile Include="NameHelpersTest.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="ReflectionTester.cs" />
<Compile Include="ReusableBuilderTest.cs" />
<Compile Include="SerializableTest.cs" />
<Compile Include="ServiceTest.cs" />
<Compile Include="TestCornerCases.cs" />
<Compile Include="TestMimeMessageFormats.cs" />
<Compile Include="TestProtos\UnitTestCSharpOptionsProtoFile.cs" />
<Compile Include="TestProtos\UnitTestCustomOptionsProtoFile.cs" />
......
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
using Google.ProtocolBuffers.Collections;
using NUnit.Framework;
using Google.ProtocolBuffers.TestProtos;
using Google.ProtocolBuffers.Serialization;
using UnitTest.Issues.TestProtos;
namespace Google.ProtocolBuffers
{
[TestFixture]
public class ReusableBuilderTest
{
[Test, Description("Issue 28: Circular message dependencies result in null defaults for DefaultInstance")]
public void EnsureStaticCicularReference()
{
MyMessageAReferenceB ab = MyMessageAReferenceB.DefaultInstance;
Assert.IsNotNull(ab);
Assert.IsNotNull(ab.Value);
MyMessageBReferenceA ba = MyMessageBReferenceA.DefaultInstance;
Assert.IsNotNull(ba);
Assert.IsNotNull(ba.Value);
}
[Test]
public void TestModifyDefaultInstance()
{
//verify that the default instance has correctly been marked as read-only
Assert.AreEqual(typeof(PopsicleList<bool>), TestAllTypes.DefaultInstance.RepeatedBoolList.GetType());
PopsicleList<bool> list = (PopsicleList<bool>)TestAllTypes.DefaultInstance.RepeatedBoolList;
Assert.IsTrue(list.IsReadOnly);
}
[Test]
public void TestUnmodifiedDefaultInstance()
{
//Simply calling ToBuilder().Build() no longer creates a copy of the message
TestAllTypes.Builder builder = TestAllTypes.DefaultInstance.ToBuilder();
Assert.IsTrue(ReferenceEquals(TestAllTypes.DefaultInstance, builder.Build()));
}
[Test]
public void BuildMultipleWithoutChange()
{
//Calling Build() or BuildPartial() does not require a copy of the message
TestAllTypes.Builder builder = TestAllTypes.DefaultInstance.ToBuilder();
builder.SetDefaultBool(true);
TestAllTypes first = builder.BuildPartial();
//Still the same instance?
Assert.IsTrue(ReferenceEquals(first, builder.Build()));
//Still the same instance?
Assert.IsTrue(ReferenceEquals(first, builder.BuildPartial().ToBuilder().Build()));
}
[Test]
public void MergeFromDefaultInstance()
{
TestAllTypes.Builder builder = TestAllTypes.DefaultInstance.ToBuilder();
Assert.IsTrue(ReferenceEquals(TestAllTypes.DefaultInstance, builder.Build()));
builder.MergeFrom(TestAllTypes.DefaultInstance);
Assert.IsTrue(ReferenceEquals(TestAllTypes.DefaultInstance, builder.Build()));
}
[Test]
public void BuildNewBuilderIsDefaultInstance()
{
Assert.IsTrue(ReferenceEquals(TestAllTypes.DefaultInstance, new TestAllTypes.Builder().Build()));
Assert.IsTrue(ReferenceEquals(TestAllTypes.DefaultInstance, TestAllTypes.CreateBuilder().Build()));
//last test, if you clear a builder it reverts to default instance
Assert.IsTrue(ReferenceEquals(TestAllTypes.DefaultInstance,
TestAllTypes.CreateBuilder().SetOptionalBool(true).Build().ToBuilder().Clear().Build()));
}
[Test]
public void BuildModifyAndRebuild()
{
TestAllTypes.Builder b1 = new TestAllTypes.Builder();
b1.SetDefaultInt32(1);
b1.AddRepeatedInt32(2);
b1.SetOptionalForeignMessage(ForeignMessage.DefaultInstance);
TestAllTypes m1 = b1.Build();
b1.SetDefaultInt32(5);
b1.AddRepeatedInt32(6);
b1.SetOptionalForeignMessage(b1.OptionalForeignMessage.ToBuilder().SetC(7));
TestAllTypes m2 = b1.Build();
Assert.AreEqual("{\"optional_foreign_message\":{},\"repeated_int32\":[2],\"default_int32\":1}", m1.ToJson());
Assert.AreEqual("{\"optional_foreign_message\":{\"c\":7},\"repeated_int32\":[2,6],\"default_int32\":5}", m2.ToJson());
}
[Test]
public void CloneOnChangePrimitive()
{
TestAllTypes.Builder builder = TestAllTypes.DefaultInstance.ToBuilder();
Assert.IsTrue(ReferenceEquals(TestAllTypes.DefaultInstance, builder.Build()));
builder.SetDefaultBool(true);
Assert.IsFalse(ReferenceEquals(TestAllTypes.DefaultInstance, builder.Build()));
}
[Test]
public void CloneOnAddRepeatedBool()
{
TestAllTypes.Builder builder = TestAllTypes.DefaultInstance.ToBuilder();
Assert.IsTrue(ReferenceEquals(TestAllTypes.DefaultInstance, builder.Build()));
builder.AddRepeatedBool(true);
Assert.IsFalse(ReferenceEquals(TestAllTypes.DefaultInstance, builder.Build()));
}
[Test]
public void CloneOnGetRepeatedBoolList()
{
TestAllTypes.Builder builder = TestAllTypes.DefaultInstance.ToBuilder();
Assert.IsTrue(ReferenceEquals(TestAllTypes.DefaultInstance, builder.Build()));
GC.KeepAlive(builder.RepeatedBoolList);
Assert.IsFalse(ReferenceEquals(TestAllTypes.DefaultInstance, builder.Build()));
}
[Test]
public void CloneOnChangeMessage()
{
TestAllTypes.Builder builder = TestAllTypes.DefaultInstance.ToBuilder();
Assert.IsTrue(ReferenceEquals(TestAllTypes.DefaultInstance, builder.Build()));
builder.SetOptionalForeignMessage(new ForeignMessage.Builder());
Assert.IsFalse(ReferenceEquals(TestAllTypes.DefaultInstance, builder.Build()));
}
[Test]
public void CloneOnClearMessage()
{
TestAllTypes.Builder builder = TestAllTypes.DefaultInstance.ToBuilder();
Assert.IsTrue(ReferenceEquals(TestAllTypes.DefaultInstance, builder.Build()));
builder.ClearOptionalForeignMessage();
Assert.IsFalse(ReferenceEquals(TestAllTypes.DefaultInstance, builder.Build()));
}
[Test]
public void CloneOnGetRepeatedForeignMessageList()
{
TestAllTypes.Builder builder = TestAllTypes.DefaultInstance.ToBuilder();
Assert.IsTrue(ReferenceEquals(TestAllTypes.DefaultInstance, builder.Build()));
GC.KeepAlive(builder.RepeatedForeignMessageList);
Assert.IsFalse(ReferenceEquals(TestAllTypes.DefaultInstance, builder.Build()));
}
[Test]
public void CloneOnChangeEnumValue()
{
TestAllTypes.Builder builder = TestAllTypes.DefaultInstance.ToBuilder();
Assert.IsTrue(ReferenceEquals(TestAllTypes.DefaultInstance, builder.Build()));
builder.SetOptionalForeignEnum(ForeignEnum.FOREIGN_BAR);
Assert.IsFalse(ReferenceEquals(TestAllTypes.DefaultInstance, builder.Build()));
}
[Test]
public void CloneOnGetRepeatedForeignEnumList()
{
TestAllTypes.Builder builder = TestAllTypes.DefaultInstance.ToBuilder();
Assert.IsTrue(ReferenceEquals(TestAllTypes.DefaultInstance, builder.Build()));
GC.KeepAlive(builder.RepeatedForeignEnumList);
Assert.IsFalse(ReferenceEquals(TestAllTypes.DefaultInstance, builder.Build()));
}
}
}
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using Google.ProtocolBuffers.TestProtos;
using NUnit.Framework;
namespace Google.ProtocolBuffers
{
[TestFixture]
public class SerializableTest
{
/// <summary>
/// Just keep it from even compiling if we these objects don't implement the expected interface.
/// </summary>
public static readonly ISerializable CompileTimeCheckSerializableMessage = TestXmlMessage.DefaultInstance;
public static readonly ISerializable CompileTimeCheckSerializableBuilder = new TestXmlMessage.Builder();
[Test]
public void TestPlainMessage()
{
TestXmlMessage message = TestXmlMessage.CreateBuilder()
.SetValid(true)
.SetText("text")
.AddTextlines("a")
.AddTextlines("b")
.AddTextlines("c")
.SetNumber(0x1010101010)
.AddNumbers(1)
.AddNumbers(2)
.AddNumbers(3)
.SetChild(TestXmlChild.CreateBuilder()
.AddOptions(EnumOptions.ONE)
.SetBinary(ByteString.CopyFrom(new byte[1])))
.AddChildren(TestXmlMessage.Types.Children.CreateBuilder()
.AddOptions(EnumOptions.TWO)
.SetBinary(ByteString.CopyFrom(new byte[2])))
.AddChildren(TestXmlMessage.Types.Children.CreateBuilder()
.AddOptions(EnumOptions.THREE)
.SetBinary(ByteString.CopyFrom(new byte[3])))
.Build();
MemoryStream ms = new MemoryStream();
new BinaryFormatter().Serialize(ms, message);
ms.Position = 0;
TestXmlMessage copy = (TestXmlMessage)new BinaryFormatter().Deserialize(ms);
Assert.AreEqual(message, copy);
}
[Test]
public void TestMessageWithExtensions()
{
TestXmlMessage message = TestXmlMessage.CreateBuilder()
.SetValid(true)
.SetText("text")
.AddTextlines("a")
.AddTextlines("b")
.AddTextlines("c")
.SetNumber(0x1010101010)
.AddNumbers(1)
.AddNumbers(2)
.AddNumbers(3)
.SetChild(TestXmlChild.CreateBuilder()
.AddOptions(EnumOptions.ONE)
.SetBinary(ByteString.CopyFrom(new byte[1])))
.AddChildren(TestXmlMessage.Types.Children.CreateBuilder()
.AddOptions(EnumOptions.TWO)
.SetBinary(ByteString.CopyFrom(new byte[2])))
.AddChildren(TestXmlMessage.Types.Children.CreateBuilder()
.AddOptions(EnumOptions.THREE)
.SetBinary(ByteString.CopyFrom(new byte[3])))
.SetExtension(UnitTestXmlSerializerTestProtoFile.ExtensionText, " extension text value ! ")
.SetExtension(UnitTestXmlSerializerTestProtoFile.ExtensionMessage, new TestXmlExtension.Builder().SetNumber(42).Build())
.AddExtension(UnitTestXmlSerializerTestProtoFile.ExtensionNumber, 100)
.AddExtension(UnitTestXmlSerializerTestProtoFile.ExtensionNumber, 101)
.AddExtension(UnitTestXmlSerializerTestProtoFile.ExtensionNumber, 102)
.SetExtension(UnitTestXmlSerializerTestProtoFile.ExtensionEnum, EnumOptions.ONE)
.Build();
ExtensionRegistry registry = ExtensionRegistry.CreateInstance();
UnitTestXmlSerializerTestProtoFile.RegisterAllExtensions(registry);
MemoryStream ms = new MemoryStream();
new BinaryFormatter().Serialize(ms, message);
ms.Position = 0;
//you need to provide the extension registry as context to the serializer
BinaryFormatter bff = new BinaryFormatter(null, new StreamingContext(StreamingContextStates.All, registry));
TestXmlMessage copy = (TestXmlMessage)bff.Deserialize(ms);
// And all extensions will be defined.
Assert.AreEqual(message, copy);
}
[Test]
public void TestPlainBuilder()
{
TestXmlMessage.Builder builder = TestXmlMessage.CreateBuilder()
.SetValid(true)
.SetText("text")
.AddTextlines("a")
.AddTextlines("b")
.AddTextlines("c")
.SetNumber(0x1010101010)
.AddNumbers(1)
.AddNumbers(2)
.AddNumbers(3)
.SetChild(TestXmlChild.CreateBuilder()
.AddOptions(EnumOptions.ONE)
.SetBinary(ByteString.CopyFrom(new byte[1])))
.AddChildren(TestXmlMessage.Types.Children.CreateBuilder()
.AddOptions(EnumOptions.TWO)
.SetBinary(ByteString.CopyFrom(new byte[2])))
.AddChildren(TestXmlMessage.Types.Children.CreateBuilder()
.AddOptions(EnumOptions.THREE)
.SetBinary(ByteString.CopyFrom(new byte[3])))
;
MemoryStream ms = new MemoryStream();
new BinaryFormatter().Serialize(ms, builder);
ms.Position = 0;
TestXmlMessage.Builder copy = (TestXmlMessage.Builder)new BinaryFormatter().Deserialize(ms);
Assert.AreEqual(builder.Build(), copy.Build());
}
[Test]
public void TestBuilderWithExtensions()
{
TestXmlMessage.Builder builder = TestXmlMessage.CreateBuilder()
.SetValid(true)
.SetText("text")
.AddTextlines("a")
.AddTextlines("b")
.AddTextlines("c")
.SetNumber(0x1010101010)
.AddNumbers(1)
.AddNumbers(2)
.AddNumbers(3)
.SetChild(TestXmlChild.CreateBuilder()
.AddOptions(EnumOptions.ONE)
.SetBinary(ByteString.CopyFrom(new byte[1])))
.AddChildren(TestXmlMessage.Types.Children.CreateBuilder()
.AddOptions(EnumOptions.TWO)
.SetBinary(ByteString.CopyFrom(new byte[2])))
.AddChildren(TestXmlMessage.Types.Children.CreateBuilder()
.AddOptions(EnumOptions.THREE)
.SetBinary(ByteString.CopyFrom(new byte[3])))
.SetExtension(UnitTestXmlSerializerTestProtoFile.ExtensionText, " extension text value ! ")
.SetExtension(UnitTestXmlSerializerTestProtoFile.ExtensionMessage, new TestXmlExtension.Builder().SetNumber(42).Build())
.AddExtension(UnitTestXmlSerializerTestProtoFile.ExtensionNumber, 100)
.AddExtension(UnitTestXmlSerializerTestProtoFile.ExtensionNumber, 101)
.AddExtension(UnitTestXmlSerializerTestProtoFile.ExtensionNumber, 102)
.SetExtension(UnitTestXmlSerializerTestProtoFile.ExtensionEnum, EnumOptions.ONE)
;
ExtensionRegistry registry = ExtensionRegistry.CreateInstance();
UnitTestXmlSerializerTestProtoFile.RegisterAllExtensions(registry);
MemoryStream ms = new MemoryStream();
new BinaryFormatter().Serialize(ms, builder);
ms.Position = 0;
//you need to provide the extension registry as context to the serializer
BinaryFormatter bff = new BinaryFormatter(null, new StreamingContext(StreamingContextStates.All, registry));
TestXmlMessage.Builder copy = (TestXmlMessage.Builder)bff.Deserialize(ms);
// And all extensions will be defined.
Assert.AreEqual(builder.Build(), copy.Build());
}
}
}
using System;
using System.Collections.Generic;
using System.Text;
using NUnit.Framework;
using UnitTest.Issues.TestProtos;
namespace Google.ProtocolBuffers
{
[TestFixture]
public class TestCornerCases
{
[Test]
public void TestRoundTripNegativeEnums()
{
NegativeEnumMessage msg = NegativeEnumMessage.CreateBuilder()
.SetValue(NegativeEnum.MinusOne) //11
.AddValues(NegativeEnum.Zero) //2
.AddValues(NegativeEnum.MinusOne) //11
.AddValues(NegativeEnum.FiveBelow) //11
//2
.AddPackedValues(NegativeEnum.Zero) //1
.AddPackedValues(NegativeEnum.MinusOne) //10
.AddPackedValues(NegativeEnum.FiveBelow) //10
.Build();
Assert.AreEqual(58, msg.SerializedSize);
byte[] bytes = new byte[58];
CodedOutputStream output = CodedOutputStream.CreateInstance(bytes);
msg.WriteTo(output);
Assert.AreEqual(0, output.SpaceLeft);
NegativeEnumMessage copy = NegativeEnumMessage.ParseFrom(bytes);
Assert.AreEqual(msg, copy);
}
}
}
// Generated by ProtoGen, Version=2.3.0.277, Culture=neutral, PublicKeyToken=17b3b1f090c3ea48. DO NOT EDIT!
#pragma warning disable 1591
#pragma warning disable 1591, 0612
#region Designer generated code
using pb = global::Google.ProtocolBuffers;
......@@ -60,7 +60,8 @@ namespace Google.ProtocolBuffers.TestProtos {
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("ProtoGen", "2.3.0.277")]
public sealed partial class OptionsMessage : pb::GeneratedMessage<OptionsMessage, OptionsMessage.Builder> {
private static readonly OptionsMessage defaultInstance = new Builder().BuildPartial();
private OptionsMessage() { }
private static readonly OptionsMessage defaultInstance = new OptionsMessage().MakeReadOnly();
private static readonly string[] _optionsMessageFieldNames = new string[] { "customized", "normal", "options_message" };
private static readonly uint[] _optionsMessageFieldTags = new uint[] { 26, 10, 18 };
public static OptionsMessage DefaultInstance {
......@@ -68,7 +69,7 @@ namespace Google.ProtocolBuffers.TestProtos {
}
public override OptionsMessage DefaultInstanceForType {
get { return defaultInstance; }
get { return DefaultInstance; }
}
protected override OptionsMessage ThisMessage {
......@@ -186,11 +187,15 @@ namespace Google.ProtocolBuffers.TestProtos {
public static OptionsMessage ParseFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed();
}
private OptionsMessage MakeReadOnly() {
return this;
}
public static Builder CreateBuilder() { return new Builder(); }
public override Builder ToBuilder() { return CreateBuilder(this); }
public override Builder CreateBuilderForType() { return new Builder(); }
public static Builder CreateBuilder(OptionsMessage prototype) {
return (Builder) new Builder().MergeFrom(prototype);
return new Builder(prototype);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
......@@ -200,22 +205,49 @@ namespace Google.ProtocolBuffers.TestProtos {
protected override Builder ThisBuilder {
get { return this; }
}
public Builder() {}
public Builder() {
result = DefaultInstance;
resultIsReadOnly = true;
}
internal Builder(OptionsMessage cloneFrom) {
result = cloneFrom;
resultIsReadOnly = true;
}
private bool resultIsReadOnly;
private OptionsMessage result;
private OptionsMessage PrepareBuilder() {
if (resultIsReadOnly) {
OptionsMessage original = result;
result = new OptionsMessage();
resultIsReadOnly = false;
MergeFrom(original);
}
return result;
}
OptionsMessage result = new OptionsMessage();
public override bool IsInitialized {
get { return result.IsInitialized; }
}
protected override OptionsMessage MessageBeingBuilt {
get { return result; }
get { return PrepareBuilder(); }
}
public override Builder Clear() {
result = new OptionsMessage();
result = DefaultInstance;
resultIsReadOnly = true;
return this;
}
public override Builder Clone() {
if (resultIsReadOnly) {
return new Builder(result);
} else {
return new Builder().MergeFrom(result);
}
}
public override pbd::MessageDescriptor DescriptorForType {
get { return global::Google.ProtocolBuffers.TestProtos.OptionsMessage.Descriptor; }
......@@ -226,12 +258,11 @@ namespace Google.ProtocolBuffers.TestProtos {
}
public override OptionsMessage BuildPartial() {
if (result == null) {
throw new global::System.InvalidOperationException("build() has already been called on this Builder");
if (resultIsReadOnly) {
return result;
}
OptionsMessage returnMe = result;
result = null;
return returnMe;
resultIsReadOnly = true;
return result.MakeReadOnly();
}
public override Builder MergeFrom(pb::IMessage other) {
......@@ -245,6 +276,7 @@ namespace Google.ProtocolBuffers.TestProtos {
public override Builder MergeFrom(OptionsMessage other) {
if (other == global::Google.ProtocolBuffers.TestProtos.OptionsMessage.DefaultInstance) return this;
PrepareBuilder();
if (other.HasNormal) {
Normal = other.Normal;
}
......@@ -263,6 +295,7 @@ namespace Google.ProtocolBuffers.TestProtos {
}
public override Builder MergeFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) {
PrepareBuilder();
pb::UnknownFieldSet.Builder unknownFields = null;
uint tag;
string field_name;
......@@ -327,11 +360,13 @@ namespace Google.ProtocolBuffers.TestProtos {
}
public Builder SetNormal(string value) {
pb::ThrowHelper.ThrowIfNull(value, "value");
PrepareBuilder();
result.hasNormal = true;
result.normal_ = value;
return this;
}
public Builder ClearNormal() {
PrepareBuilder();
result.hasNormal = false;
result.normal_ = "";
return this;
......@@ -346,11 +381,13 @@ namespace Google.ProtocolBuffers.TestProtos {
}
public Builder SetOptionsMessage_(string value) {
pb::ThrowHelper.ThrowIfNull(value, "value");
PrepareBuilder();
result.hasOptionsMessage_ = true;
result.optionsMessage_ = value;
return this;
}
public Builder ClearOptionsMessage_() {
PrepareBuilder();
result.hasOptionsMessage_ = false;
result.optionsMessage_ = "";
return this;
......@@ -365,11 +402,13 @@ namespace Google.ProtocolBuffers.TestProtos {
}
public Builder SetCustomName(string value) {
pb::ThrowHelper.ThrowIfNull(value, "value");
PrepareBuilder();
result.hasCustomName = true;
result.customized_ = value;
return this;
}
public Builder ClearCustomName() {
PrepareBuilder();
result.hasCustomName = false;
result.customized_ = "";
return this;
......
This source diff could not be displayed because it is too large. You can view the blob instead.
// Generated by ProtoGen, Version=2.3.0.277, Culture=neutral, PublicKeyToken=17b3b1f090c3ea48. DO NOT EDIT!
#pragma warning disable 1591
#pragma warning disable 1591, 0612
#region Designer generated code
using pb = global::Google.ProtocolBuffers;
......
// Generated by ProtoGen, Version=2.3.0.277, Culture=neutral, PublicKeyToken=17b3b1f090c3ea48. DO NOT EDIT!
#pragma warning disable 1591
#pragma warning disable 1591, 0612
#region Designer generated code
using pb = global::Google.ProtocolBuffers;
......
// Generated by ProtoGen, Version=2.3.0.277, Culture=neutral, PublicKeyToken=17b3b1f090c3ea48. DO NOT EDIT!
#pragma warning disable 1591
#pragma warning disable 1591, 0612
#region Designer generated code
using pb = global::Google.ProtocolBuffers;
......@@ -43,7 +43,8 @@ namespace Google.ProtocolBuffers.TestProtos {
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("ProtoGen", "2.3.0.277")]
public sealed partial class ImportMessageLite : pb::GeneratedMessageLite<ImportMessageLite, ImportMessageLite.Builder> {
private static readonly ImportMessageLite defaultInstance = new Builder().BuildPartial();
private ImportMessageLite() { }
private static readonly ImportMessageLite defaultInstance = new ImportMessageLite().MakeReadOnly();
private static readonly string[] _importMessageLiteFieldNames = new string[] { "d" };
private static readonly uint[] _importMessageLiteFieldTags = new uint[] { 8 };
public static ImportMessageLite DefaultInstance {
......@@ -51,7 +52,7 @@ namespace Google.ProtocolBuffers.TestProtos {
}
public override ImportMessageLite DefaultInstanceForType {
get { return defaultInstance; }
get { return DefaultInstance; }
}
protected override ImportMessageLite ThisMessage {
......@@ -146,11 +147,15 @@ namespace Google.ProtocolBuffers.TestProtos {
public static ImportMessageLite ParseFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed();
}
private ImportMessageLite MakeReadOnly() {
return this;
}
public static Builder CreateBuilder() { return new Builder(); }
public override Builder ToBuilder() { return CreateBuilder(this); }
public override Builder CreateBuilderForType() { return new Builder(); }
public static Builder CreateBuilder(ImportMessageLite prototype) {
return (Builder) new Builder().MergeFrom(prototype);
return new Builder(prototype);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
......@@ -160,34 +165,60 @@ namespace Google.ProtocolBuffers.TestProtos {
protected override Builder ThisBuilder {
get { return this; }
}
public Builder() {}
public Builder() {
result = DefaultInstance;
resultIsReadOnly = true;
}
internal Builder(ImportMessageLite cloneFrom) {
result = cloneFrom;
resultIsReadOnly = true;
}
private bool resultIsReadOnly;
private ImportMessageLite result;
private ImportMessageLite PrepareBuilder() {
if (resultIsReadOnly) {
ImportMessageLite original = result;
result = new ImportMessageLite();
resultIsReadOnly = false;
MergeFrom(original);
}
return result;
}
ImportMessageLite result = new ImportMessageLite();
public override bool IsInitialized {
get { return result.IsInitialized; }
}
protected override ImportMessageLite MessageBeingBuilt {
get { return result; }
get { return PrepareBuilder(); }
}
public override Builder Clear() {
result = new ImportMessageLite();
result = DefaultInstance;
resultIsReadOnly = true;
return this;
}
public override Builder Clone() {
if (resultIsReadOnly) {
return new Builder(result);
} else {
return new Builder().MergeFrom(result);
}
}
public override ImportMessageLite DefaultInstanceForType {
get { return global::Google.ProtocolBuffers.TestProtos.ImportMessageLite.DefaultInstance; }
}
public override ImportMessageLite BuildPartial() {
if (result == null) {
throw new global::System.InvalidOperationException("build() has already been called on this Builder");
if (resultIsReadOnly) {
return result;
}
ImportMessageLite returnMe = result;
result = null;
return returnMe;
resultIsReadOnly = true;
return result.MakeReadOnly();
}
public override Builder MergeFrom(pb::IMessageLite other) {
......@@ -201,6 +232,7 @@ namespace Google.ProtocolBuffers.TestProtos {
public override Builder MergeFrom(ImportMessageLite other) {
if (other == global::Google.ProtocolBuffers.TestProtos.ImportMessageLite.DefaultInstance) return this;
PrepareBuilder();
if (other.HasD) {
D = other.D;
}
......@@ -212,6 +244,7 @@ namespace Google.ProtocolBuffers.TestProtos {
}
public override Builder MergeFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) {
PrepareBuilder();
uint tag;
string field_name;
while (input.ReadTag(out tag, out field_name)) {
......@@ -254,11 +287,13 @@ namespace Google.ProtocolBuffers.TestProtos {
set { SetD(value); }
}
public Builder SetD(int value) {
PrepareBuilder();
result.hasD = true;
result.d_ = value;
return this;
}
public Builder ClearD() {
PrepareBuilder();
result.hasD = false;
result.d_ = 0;
return this;
......
// Generated by ProtoGen, Version=2.3.0.277, Culture=neutral, PublicKeyToken=17b3b1f090c3ea48. DO NOT EDIT!
#pragma warning disable 1591
#pragma warning disable 1591, 0612
#region Designer generated code
using pb = global::Google.ProtocolBuffers;
......@@ -71,7 +71,8 @@ namespace Google.ProtocolBuffers.TestProtos {
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("ProtoGen", "2.3.0.277")]
public sealed partial class ImportMessage : pb::GeneratedMessage<ImportMessage, ImportMessage.Builder> {
private static readonly ImportMessage defaultInstance = new Builder().BuildPartial();
private ImportMessage() { }
private static readonly ImportMessage defaultInstance = new ImportMessage().MakeReadOnly();
private static readonly string[] _importMessageFieldNames = new string[] { "d" };
private static readonly uint[] _importMessageFieldTags = new uint[] { 8 };
public static ImportMessage DefaultInstance {
......@@ -79,7 +80,7 @@ namespace Google.ProtocolBuffers.TestProtos {
}
public override ImportMessage DefaultInstanceForType {
get { return defaultInstance; }
get { return DefaultInstance; }
}
protected override ImportMessage ThisMessage {
......@@ -165,11 +166,15 @@ namespace Google.ProtocolBuffers.TestProtos {
public static ImportMessage ParseFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed();
}
private ImportMessage MakeReadOnly() {
return this;
}
public static Builder CreateBuilder() { return new Builder(); }
public override Builder ToBuilder() { return CreateBuilder(this); }
public override Builder CreateBuilderForType() { return new Builder(); }
public static Builder CreateBuilder(ImportMessage prototype) {
return (Builder) new Builder().MergeFrom(prototype);
return new Builder(prototype);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
......@@ -179,22 +184,49 @@ namespace Google.ProtocolBuffers.TestProtos {
protected override Builder ThisBuilder {
get { return this; }
}
public Builder() {}
public Builder() {
result = DefaultInstance;
resultIsReadOnly = true;
}
internal Builder(ImportMessage cloneFrom) {
result = cloneFrom;
resultIsReadOnly = true;
}
private bool resultIsReadOnly;
private ImportMessage result;
private ImportMessage PrepareBuilder() {
if (resultIsReadOnly) {
ImportMessage original = result;
result = new ImportMessage();
resultIsReadOnly = false;
MergeFrom(original);
}
return result;
}
ImportMessage result = new ImportMessage();
public override bool IsInitialized {
get { return result.IsInitialized; }
}
protected override ImportMessage MessageBeingBuilt {
get { return result; }
get { return PrepareBuilder(); }
}
public override Builder Clear() {
result = new ImportMessage();
result = DefaultInstance;
resultIsReadOnly = true;
return this;
}
public override Builder Clone() {
if (resultIsReadOnly) {
return new Builder(result);
} else {
return new Builder().MergeFrom(result);
}
}
public override pbd::MessageDescriptor DescriptorForType {
get { return global::Google.ProtocolBuffers.TestProtos.ImportMessage.Descriptor; }
......@@ -205,12 +237,11 @@ namespace Google.ProtocolBuffers.TestProtos {
}
public override ImportMessage BuildPartial() {
if (result == null) {
throw new global::System.InvalidOperationException("build() has already been called on this Builder");
if (resultIsReadOnly) {
return result;
}
ImportMessage returnMe = result;
result = null;
return returnMe;
resultIsReadOnly = true;
return result.MakeReadOnly();
}
public override Builder MergeFrom(pb::IMessage other) {
......@@ -224,6 +255,7 @@ namespace Google.ProtocolBuffers.TestProtos {
public override Builder MergeFrom(ImportMessage other) {
if (other == global::Google.ProtocolBuffers.TestProtos.ImportMessage.DefaultInstance) return this;
PrepareBuilder();
if (other.HasD) {
D = other.D;
}
......@@ -236,6 +268,7 @@ namespace Google.ProtocolBuffers.TestProtos {
}
public override Builder MergeFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) {
PrepareBuilder();
pb::UnknownFieldSet.Builder unknownFields = null;
uint tag;
string field_name;
......@@ -291,11 +324,13 @@ namespace Google.ProtocolBuffers.TestProtos {
set { SetD(value); }
}
public Builder SetD(int value) {
PrepareBuilder();
result.hasD = true;
result.d_ = value;
return this;
}
public Builder ClearD() {
PrepareBuilder();
result.hasD = false;
result.d_ = 0;
return this;
......
// Generated by ProtoGen, Version=2.3.0.277, Culture=neutral, PublicKeyToken=17b3b1f090c3ea48. DO NOT EDIT!
#pragma warning disable 1591
#pragma warning disable 1591, 0612
#region Designer generated code
using pb = global::Google.ProtocolBuffers;
......@@ -81,7 +81,8 @@ namespace Google.ProtocolBuffers.TestProtos.NoGenericService {
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("ProtoGen", "2.3.0.277")]
public sealed partial class TestMessage : pb::ExtendableMessage<TestMessage, TestMessage.Builder> {
private static readonly TestMessage defaultInstance = new Builder().BuildPartial();
private TestMessage() { }
private static readonly TestMessage defaultInstance = new TestMessage().MakeReadOnly();
private static readonly string[] _testMessageFieldNames = new string[] { "a" };
private static readonly uint[] _testMessageFieldTags = new uint[] { 8 };
public static TestMessage DefaultInstance {
......@@ -89,7 +90,7 @@ namespace Google.ProtocolBuffers.TestProtos.NoGenericService {
}
public override TestMessage DefaultInstanceForType {
get { return defaultInstance; }
get { return DefaultInstance; }
}
protected override TestMessage ThisMessage {
......@@ -179,11 +180,15 @@ namespace Google.ProtocolBuffers.TestProtos.NoGenericService {
public static TestMessage ParseFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed();
}
private TestMessage MakeReadOnly() {
return this;
}
public static Builder CreateBuilder() { return new Builder(); }
public override Builder ToBuilder() { return CreateBuilder(this); }
public override Builder CreateBuilderForType() { return new Builder(); }
public static Builder CreateBuilder(TestMessage prototype) {
return (Builder) new Builder().MergeFrom(prototype);
return new Builder(prototype);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
......@@ -193,22 +198,49 @@ namespace Google.ProtocolBuffers.TestProtos.NoGenericService {
protected override Builder ThisBuilder {
get { return this; }
}
public Builder() {}
public Builder() {
result = DefaultInstance;
resultIsReadOnly = true;
}
internal Builder(TestMessage cloneFrom) {
result = cloneFrom;
resultIsReadOnly = true;
}
private bool resultIsReadOnly;
private TestMessage result;
private TestMessage PrepareBuilder() {
if (resultIsReadOnly) {
TestMessage original = result;
result = new TestMessage();
resultIsReadOnly = false;
MergeFrom(original);
}
return result;
}
TestMessage result = new TestMessage();
public override bool IsInitialized {
get { return result.IsInitialized; }
}
protected override TestMessage MessageBeingBuilt {
get { return result; }
get { return PrepareBuilder(); }
}
public override Builder Clear() {
result = new TestMessage();
result = DefaultInstance;
resultIsReadOnly = true;
return this;
}
public override Builder Clone() {
if (resultIsReadOnly) {
return new Builder(result);
} else {
return new Builder().MergeFrom(result);
}
}
public override pbd::MessageDescriptor DescriptorForType {
get { return global::Google.ProtocolBuffers.TestProtos.NoGenericService.TestMessage.Descriptor; }
......@@ -219,12 +251,11 @@ namespace Google.ProtocolBuffers.TestProtos.NoGenericService {
}
public override TestMessage BuildPartial() {
if (result == null) {
throw new global::System.InvalidOperationException("build() has already been called on this Builder");
if (resultIsReadOnly) {
return result;
}
TestMessage returnMe = result;
result = null;
return returnMe;
resultIsReadOnly = true;
return result.MakeReadOnly();
}
public override Builder MergeFrom(pb::IMessage other) {
......@@ -238,6 +269,7 @@ namespace Google.ProtocolBuffers.TestProtos.NoGenericService {
public override Builder MergeFrom(TestMessage other) {
if (other == global::Google.ProtocolBuffers.TestProtos.NoGenericService.TestMessage.DefaultInstance) return this;
PrepareBuilder();
if (other.HasA) {
A = other.A;
}
......@@ -251,6 +283,7 @@ namespace Google.ProtocolBuffers.TestProtos.NoGenericService {
}
public override Builder MergeFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) {
PrepareBuilder();
pb::UnknownFieldSet.Builder unknownFields = null;
uint tag;
string field_name;
......@@ -306,11 +339,13 @@ namespace Google.ProtocolBuffers.TestProtos.NoGenericService {
set { SetA(value); }
}
public Builder SetA(int value) {
PrepareBuilder();
result.hasA = true;
result.a_ = value;
return this;
}
public Builder ClearA() {
PrepareBuilder();
result.hasA = false;
result.a_ = 0;
return this;
......
......@@ -44,7 +44,7 @@ namespace Google.ProtocolBuffers
/// <summary>
/// Implementation of the non-generic IMessage interface as far as possible.
/// </summary>
public abstract class AbstractBuilder<TMessage, TBuilder> : AbstractBuilderLite<TMessage, TBuilder>,
public abstract partial class AbstractBuilder<TMessage, TBuilder> : AbstractBuilderLite<TMessage, TBuilder>,
IBuilder<TMessage, TBuilder>
where TMessage : AbstractMessage<TMessage, TBuilder>
where TBuilder : AbstractBuilder<TMessage, TBuilder>
......
......@@ -42,7 +42,7 @@ namespace Google.ProtocolBuffers
/// <summary>
/// Implementation of the non-generic IMessage interface as far as possible.
/// </summary>
public abstract class AbstractBuilderLite<TMessage, TBuilder> : IBuilderLite<TMessage, TBuilder>
public abstract partial class AbstractBuilderLite<TMessage, TBuilder> : IBuilderLite<TMessage, TBuilder>
where TMessage : AbstractMessageLite<TMessage, TBuilder>
where TBuilder : AbstractBuilderLite<TMessage, TBuilder>
{
......
......@@ -46,7 +46,7 @@ namespace Google.ProtocolBuffers
/// <summary>
/// Implementation of the non-generic IMessage interface as far as possible.
/// </summary>
public abstract class AbstractMessage<TMessage, TBuilder> : AbstractMessageLite<TMessage, TBuilder>,
public abstract partial class AbstractMessage<TMessage, TBuilder> : AbstractMessageLite<TMessage, TBuilder>,
IMessage<TMessage, TBuilder>
where TMessage : AbstractMessage<TMessage, TBuilder>
where TBuilder : AbstractBuilder<TMessage, TBuilder>
......
......@@ -41,7 +41,7 @@ namespace Google.ProtocolBuffers
/// <summary>
/// Implementation of the non-generic IMessage interface as far as possible.
/// </summary>
public abstract class AbstractMessageLite<TMessage, TBuilder> : IMessageLite<TMessage, TBuilder>
public abstract partial class AbstractMessageLite<TMessage, TBuilder> : IMessageLite<TMessage, TBuilder>
where TMessage : AbstractMessageLite<TMessage, TBuilder>
where TBuilder : AbstractBuilderLite<TMessage, TBuilder>
{
......
......@@ -202,7 +202,7 @@ namespace Google.ProtocolBuffers
/// </summary>
public static int ComputeEnumSize(int fieldNumber, int value)
{
return ComputeTagSize(fieldNumber) + ComputeRawVarint32Size((uint) value);
return ComputeTagSize(fieldNumber) + ComputeEnumSizeNoTag(value);
}
/// <summary>
......@@ -391,7 +391,7 @@ namespace Google.ProtocolBuffers
/// </summary>
public static int ComputeEnumSizeNoTag(int value)
{
return ComputeRawVarint32Size((uint) value);
return ComputeInt32SizeNoTag(value);
}
/// <summary>
......
......@@ -388,7 +388,7 @@ namespace Google.ProtocolBuffers
public void WriteEnum(int fieldNumber, string fieldName, int value, object rawValue)
{
WriteTag(fieldNumber, WireFormat.WireType.Varint);
WriteRawVarint32((uint) value);
WriteInt32NoTag(value);
}
public void WriteSFixed32(int fieldNumber, string fieldName, int value)
......@@ -663,7 +663,7 @@ namespace Google.ProtocolBuffers
public void WriteEnumNoTag(int value)
{
WriteRawVarint32((uint) value);
WriteInt32NoTag(value);
}
public void WriteSFixed32NoTag(int value)
......
......@@ -42,6 +42,7 @@ namespace Google.ProtocolBuffers.Collections
/// </summary>
public sealed class PopsicleList<T> : IPopsicleList<T>, ICastArray
{
private static readonly bool CheckForNull = default(T) == null;
private static readonly T[] EmptySet = new T[0];
private List<T> items;
......@@ -65,6 +66,10 @@ namespace Google.ProtocolBuffers.Collections
public void Insert(int index, T item)
{
ValidateModification();
if (CheckForNull)
{
ThrowHelper.ThrowIfNull(item);
}
items.Insert(index, item);
}
......@@ -87,6 +92,10 @@ namespace Google.ProtocolBuffers.Collections
set
{
ValidateModification();
if (CheckForNull)
{
ThrowHelper.ThrowIfNull(value);
}
items[index] = value;
}
}
......@@ -94,6 +103,10 @@ namespace Google.ProtocolBuffers.Collections
public void Add(T item)
{
ValidateModification();
if (CheckForNull)
{
ThrowHelper.ThrowIfNull(item);
}
items.Add(item);
}
......@@ -145,16 +158,31 @@ namespace Google.ProtocolBuffers.Collections
public void Add(IEnumerable<T> collection)
{
if (readOnly)
ValidateModification();
ThrowHelper.ThrowIfNull(collection);
if (!CheckForNull || collection is PopsicleList<T>)
{
throw new NotSupportedException("List is read-only");
items.AddRange(collection);
}
if (items == null)
else
{
items = new List<T>();
}
// Assumption, it's ok to enumerate collections more than once.
if (collection is ICollection<T>)
{
ThrowHelper.ThrowIfAnyNull(collection);
items.AddRange(collection);
}
else
{
foreach (T item in collection)
{
ThrowHelper.ThrowIfNull(item);
items.Add(item);
}
}
}
}
private void ValidateModification()
{
......
#region Copyright notice and license
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://github.com/jskeet/dotnet-protobufs/
// Original C++/Java/Python code:
// http://code.google.com/p/protobuf/
//
// 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.Runtime.Serialization;
/*
* This entire source file is not supported on the Silverlight platform
*/
#if !SILVERLIGHT2
namespace Google.ProtocolBuffers
{
/*
* Specialized handing of *all* message types. Messages are serialized into a byte[] and stored
* into the SerializationInfo, and are then reconstituted by an IObjectReference class after
* deserialization. IDeserializationCallback is supported on both the Builder and Message.
*/
[Serializable]
partial class AbstractMessageLite<TMessage, TBuilder> : ISerializable
{
void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
{
info.SetType(typeof(SerializationSurrogate));
info.AddValue("message", ToByteArray());
info.AddValue("initialized", IsInitialized);
}
[Serializable]
private sealed class SerializationSurrogate : IObjectReference, ISerializable
{
static readonly TBuilder TemplateInstance = (TBuilder)Activator.CreateInstance(typeof(TBuilder));
private readonly byte[] _message;
private readonly bool _initialized;
private SerializationSurrogate(SerializationInfo info, StreamingContext context)
{
_message = (byte[])info.GetValue("message", typeof(byte[]));
_initialized = info.GetBoolean("initialized");
}
object IObjectReference.GetRealObject(StreamingContext context)
{
ExtensionRegistry registry = context.Context as ExtensionRegistry;
TBuilder builder = TemplateInstance.DefaultInstanceForType.CreateBuilderForType();
builder.MergeFrom(_message, registry ?? ExtensionRegistry.Empty);
IDeserializationCallback callback = builder as IDeserializationCallback;
if(callback != null)
{
callback.OnDeserialization(context);
}
TMessage message = _initialized ? builder.Build() : builder.BuildPartial();
callback = message as IDeserializationCallback;
if (callback != null)
{
callback.OnDeserialization(context);
}
return message;
}
void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
{
info.AddValue("message", _message);
}
}
}
[Serializable]
partial class AbstractBuilderLite<TMessage, TBuilder> : ISerializable
{
void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
{
info.SetType(typeof(SerializationSurrogate));
info.AddValue("message", Clone().BuildPartial().ToByteArray());
}
[Serializable]
private sealed class SerializationSurrogate : IObjectReference, ISerializable
{
static readonly TBuilder TemplateInstance = (TBuilder)Activator.CreateInstance(typeof(TBuilder));
private readonly byte[] _message;
private SerializationSurrogate(SerializationInfo info, StreamingContext context)
{
_message = (byte[])info.GetValue("message", typeof(byte[]));
}
object IObjectReference.GetRealObject(StreamingContext context)
{
ExtensionRegistry registry = context.Context as ExtensionRegistry;
TBuilder builder = TemplateInstance.DefaultInstanceForType.CreateBuilderForType();
builder.MergeFrom(_message, registry ?? ExtensionRegistry.Empty);
IDeserializationCallback callback = builder as IDeserializationCallback;
if(callback != null)
{
callback.OnDeserialization(context);
}
return builder;
}
void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
{
info.AddValue("message", _message);
}
}
}
/*
* Spread some attribute love around, keeping this all here so we don't use conditional compliation
* in every one of these classes. If we introduce a new platform that also does not support this
* we can control it all from this source file.
*/
[Serializable]
partial class GeneratedMessageLite<TMessage, TBuilder> { }
[Serializable]
partial class ExtendableMessageLite<TMessage, TBuilder> { }
[Serializable]
partial class AbstractMessage<TMessage, TBuilder> { }
[Serializable]
partial class GeneratedMessage<TMessage, TBuilder> { }
[Serializable]
partial class ExtendableMessage<TMessage, TBuilder> { }
[Serializable]
partial class GeneratedBuilderLite<TMessage, TBuilder> { }
[Serializable]
partial class ExtendableBuilderLite<TMessage, TBuilder> { }
[Serializable]
partial class AbstractBuilder<TMessage, TBuilder> { }
[Serializable]
partial class GeneratedBuilder<TMessage, TBuilder> { }
[Serializable]
partial class ExtendableBuilder<TMessage, TBuilder> { }
[Serializable]
partial class DynamicMessage
{
[Serializable]
partial class Builder { }
}
}
#endif
\ No newline at end of file
......@@ -44,7 +44,7 @@ namespace Google.ProtocolBuffers
/// <summary>
/// An implementation of IMessage that can represent arbitrary types, given a MessageaDescriptor.
/// </summary>
public sealed class DynamicMessage : AbstractMessage<DynamicMessage, DynamicMessage.Builder>
public sealed partial class DynamicMessage : AbstractMessage<DynamicMessage, DynamicMessage.Builder>
{
private readonly MessageDescriptor type;
private readonly FieldSet fields;
......@@ -308,7 +308,7 @@ namespace Google.ProtocolBuffers
/// <summary>
/// Builder for dynamic messages. Instances are created with DynamicMessage.CreateBuilder.
/// </summary>
public sealed class Builder : AbstractBuilder<DynamicMessage, Builder>
public sealed partial class Builder : AbstractBuilder<DynamicMessage, Builder>
{
private readonly MessageDescriptor type;
private FieldSet fields;
......
......@@ -40,7 +40,7 @@ using Google.ProtocolBuffers.Descriptors;
namespace Google.ProtocolBuffers
{
public abstract class ExtendableBuilder<TMessage, TBuilder> : GeneratedBuilder<TMessage, TBuilder>
public abstract partial class ExtendableBuilder<TMessage, TBuilder> : GeneratedBuilder<TMessage, TBuilder>
where TMessage : ExtendableMessage<TMessage, TBuilder>
where TBuilder : GeneratedBuilder<TMessage, TBuilder>, new()
{
......
......@@ -40,7 +40,7 @@ using Google.ProtocolBuffers.Descriptors;
namespace Google.ProtocolBuffers
{
public abstract class ExtendableBuilderLite<TMessage, TBuilder> : GeneratedBuilderLite<TMessage, TBuilder>
public abstract partial class ExtendableBuilderLite<TMessage, TBuilder> : GeneratedBuilderLite<TMessage, TBuilder>
where TMessage : ExtendableMessageLite<TMessage, TBuilder>
where TBuilder : GeneratedBuilderLite<TMessage, TBuilder>
{
......
......@@ -41,7 +41,7 @@ using Google.ProtocolBuffers.Descriptors;
namespace Google.ProtocolBuffers
{
public abstract class ExtendableMessage<TMessage, TBuilder> : GeneratedMessage<TMessage, TBuilder>
public abstract partial class ExtendableMessage<TMessage, TBuilder> : GeneratedMessage<TMessage, TBuilder>
where TMessage : GeneratedMessage<TMessage, TBuilder>
where TBuilder : GeneratedBuilder<TMessage, TBuilder>, new()
{
......
......@@ -42,7 +42,7 @@ using Google.ProtocolBuffers.Collections;
namespace Google.ProtocolBuffers
{
public abstract class ExtendableMessageLite<TMessage, TBuilder> : GeneratedMessageLite<TMessage, TBuilder>
public abstract partial class ExtendableMessageLite<TMessage, TBuilder> : GeneratedMessageLite<TMessage, TBuilder>
where TMessage : GeneratedMessageLite<TMessage, TBuilder>
where TBuilder : GeneratedBuilderLite<TMessage, TBuilder>
{
......
......@@ -47,7 +47,7 @@ namespace Google.ProtocolBuffers
/// most of the IBuilder interface using reflection. Users can ignore this class
/// as an implementation detail.
/// </summary>
public abstract class GeneratedBuilder<TMessage, TBuilder> : AbstractBuilder<TMessage, TBuilder>
public abstract partial class GeneratedBuilder<TMessage, TBuilder> : AbstractBuilder<TMessage, TBuilder>
where TMessage : GeneratedMessage<TMessage, TBuilder>
where TBuilder : GeneratedBuilder<TMessage, TBuilder>, new()
{
......@@ -58,12 +58,7 @@ namespace Google.ProtocolBuffers
protected internal FieldAccessorTable<TMessage, TBuilder> InternalFieldAccessors
{
get { return MessageBeingBuilt.FieldAccessorsFromBuilder; }
}
public override bool IsInitialized
{
get { return MessageBeingBuilt.IsInitialized; }
get { return DefaultInstanceForType.FieldAccessorsFromBuilder; }
}
public override IDictionary<FieldDescriptor, object> AllFields
......@@ -84,32 +79,6 @@ namespace Google.ProtocolBuffers
set { InternalFieldAccessors[field].SetValue(ThisBuilder, value); }
}
/// <summary>
/// Adds all of the specified values to the given collection.
/// </summary>
/// <exception cref="ArgumentNullException">Any element of the list is null</exception>
protected void AddRange<T>(IEnumerable<T> source, IList<T> destination)
{
ThrowHelper.ThrowIfNull(source);
// We only need to check this for nullable types.
if (default(T) == null)
{
ThrowHelper.ThrowIfAnyNull(source);
}
List<T> list = destination as List<T>;
if (list != null)
{
list.AddRange(source);
}
else
{
foreach (T element in source)
{
destination.Add(element);
}
}
}
/// <summary>
/// Called by derived classes to parse an unknown field.
/// </summary>
......@@ -123,7 +92,7 @@ namespace Google.ProtocolBuffers
public override MessageDescriptor DescriptorForType
{
get { return MessageBeingBuilt.DescriptorForType; }
get { return DefaultInstanceForType.DescriptorForType; }
}
public override int GetRepeatedFieldCount(FieldDescriptor field)
......@@ -230,7 +199,7 @@ namespace Google.ProtocolBuffers
public override TMessage Build()
{
// If the message is null, we'll throw a more appropriate exception in BuildPartial.
if (MessageBeingBuilt != null && !IsInitialized)
if (!IsInitialized)
{
throw new UninitializedMessageException(MessageBeingBuilt);
}
......
......@@ -44,7 +44,7 @@ namespace Google.ProtocolBuffers
/// most of the IBuilder interface using reflection. Users can ignore this class
/// as an implementation detail.
/// </summary>
public abstract class GeneratedBuilderLite<TMessage, TBuilder> : AbstractBuilderLite<TMessage, TBuilder>
public abstract partial class GeneratedBuilderLite<TMessage, TBuilder> : AbstractBuilderLite<TMessage, TBuilder>
where TMessage : GeneratedMessageLite<TMessage, TBuilder>
where TBuilder : GeneratedBuilderLite<TMessage, TBuilder>
{
......@@ -61,37 +61,6 @@ namespace Google.ProtocolBuffers
public abstract TBuilder MergeFrom(TMessage other);
public override bool IsInitialized
{
get { return MessageBeingBuilt.IsInitialized; }
}
/// <summary>
/// Adds all of the specified values to the given collection.
/// </summary>
/// <exception cref="ArgumentNullException">Any element of the list is null</exception>
protected void AddRange<T>(IEnumerable<T> source, IList<T> destination)
{
ThrowHelper.ThrowIfNull(source);
// We only need to check this for nullable types.
if (default(T) == null)
{
ThrowHelper.ThrowIfAnyNull(source);
}
List<T> list = destination as List<T>;
if (list != null)
{
list.AddRange(source);
}
else
{
foreach (T element in source)
{
destination.Add(element);
}
}
}
/// <summary>
/// Called by derived classes to parse an unknown field.
/// </summary>
......@@ -122,7 +91,7 @@ namespace Google.ProtocolBuffers
public override TMessage Build()
{
// If the message is null, we'll throw a more appropriate exception in BuildPartial.
if (MessageBeingBuilt != null && !IsInitialized)
if (!IsInitialized)
{
throw new UninitializedMessageException(MessageBeingBuilt);
}
......
......@@ -50,7 +50,7 @@ namespace Google.ProtocolBuffers
/// most of the IMessage interface using reflection. Users
/// can ignore this class as an implementation detail.
/// </summary>
public abstract class GeneratedMessage<TMessage, TBuilder> : AbstractMessage<TMessage, TBuilder>
public abstract partial class GeneratedMessage<TMessage, TBuilder> : AbstractMessage<TMessage, TBuilder>
where TMessage : GeneratedMessage<TMessage, TBuilder>
where TBuilder : GeneratedBuilder<TMessage, TBuilder>, new()
{
......
......@@ -47,7 +47,7 @@ namespace Google.ProtocolBuffers
/// most of the IMessage interface using reflection. Users
/// can ignore this class as an implementation detail.
/// </summary>
public abstract class GeneratedMessageLite<TMessage, TBuilder> : AbstractMessageLite<TMessage, TBuilder>
public abstract partial class GeneratedMessageLite<TMessage, TBuilder> : AbstractMessageLite<TMessage, TBuilder>
where TMessage : GeneratedMessageLite<TMessage, TBuilder>
where TBuilder : GeneratedBuilderLite<TMessage, TBuilder>
{
......
......@@ -46,7 +46,7 @@ namespace Google.ProtocolBuffers
/// use explicit interface implemenation for the non-generic form. This mirrors
/// how IEnumerable and IEnumerable&lt;T&gt; work.
/// </summary>
public interface IBuilderLite
public partial interface IBuilderLite
{
/// <summary>
/// Returns true iff all required fields in the message and all
......
......@@ -42,7 +42,7 @@ namespace Google.ProtocolBuffers
/// Non-generic interface used for all parts of the API which don't require
/// any type knowledge.
/// </summary>
public interface IMessageLite
public partial interface IMessageLite
{
/// <summary>
/// Returns true iff all required fields in the message and all embedded
......
......@@ -105,7 +105,7 @@ namespace Google.ProtocolBuffers
/// well give up on replying to it. This method must be called on the server
/// side only. The server should still call the final "done" callback.
/// </summary>
bool isCanceled();
bool IsCanceled();
/// <summary>
/// Requests that the given callback be called when the RPC is canceled.
......
......@@ -34,18 +34,42 @@
#endregion
using System;
namespace Google.ProtocolBuffers
{
/// <summary>
///
/// Provides an entry-point for transport listeners to call a specified method on a service
/// </summary>
public interface IRpcServerStub
public interface IRpcServerStub : IDisposable
{
/// <summary>
/// Calls the method identified by methodName and returns the message
/// </summary>
/// <param name="methodName">The method name on the service descriptor (case-sensitive)</param>
/// <param name="input">The ICodedInputStream to deserialize the call parameter from</param>
/// <param name="registry">The extension registry to use when deserializing the call parameter</param>
/// <returns>The message that was returned from the service's method</returns>
IMessageLite CallMethod(string methodName, ICodedInputStream input, ExtensionRegistry registry);
}
/// <summary>
/// Used to forward an invocation of a service method to a transport sender implementation
/// </summary>
public interface IRpcDispatch
{
/// <summary>
/// Calls the service member on the endpoint connected. This is generally done by serializing
/// the message, sending the bytes over a transport, and then deserializing the call parameter
/// to invoke the service's actual implementation via IRpcServerStub. Once the call has
/// completed the result message is serialized and returned to the originating endpoint.
/// </summary>
/// <typeparam name="TMessage">The type of the response message</typeparam>
/// <typeparam name="TBuilder">The type of of the response builder</typeparam>
/// <param name="method">The name of the method on the service</param>
/// <param name="request">The message instance provided to the service call</param>
/// <param name="response">The builder used to deserialize the response</param>
/// <returns>The resulting message of the service call</returns>
TMessage CallMethod<TMessage, TBuilder>(string method, IMessageLite request,
IBuilderLite<TMessage, TBuilder> response)
where TMessage : IMessageLite<TMessage, TBuilder>
......
......@@ -105,6 +105,7 @@
<Compile Include="Collections\IPopsicleList.cs" />
<Compile Include="Collections\PopsicleList.cs" />
<Compile Include="CodedOutputStream.ComputeSize.cs" />
<Compile Include="CustomSerialization.cs" />
<Compile Include="Delegates.cs" />
<Compile Include="CodedInputStream.cs" />
<Compile Include="CodedOutputStream.cs" />
......
......@@ -86,6 +86,7 @@
<Compile Include="Collections\Lists.cs" />
<Compile Include="Collections\PopsicleList.cs" />
<Compile Include="Collections\ReadOnlyDictionary.cs" />
<Compile Include="CustomSerialization.cs" />
<Compile Include="Descriptors\FieldMappingAttribute.cs" />
<Compile Include="Descriptors\FieldType.cs" />
<Compile Include="Descriptors\MappedType.cs" />
......
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment