Commit 74c5e0c3 authored by csharptest's avatar csharptest Committed by rogerk

Reformatted to include braces

parent afff2c65
...@@ -112,7 +112,8 @@ namespace Google.ProtocolBuffers.ProtoGen ...@@ -112,7 +112,8 @@ namespace Google.ProtocolBuffers.ProtoGen
public void GenerateSerializationCode(TextGenerator writer) public void GenerateSerializationCode(TextGenerator writer)
{ {
writer.WriteLine("if (has{0}) {{", PropertyName); writer.WriteLine("if (has{0}) {{", PropertyName);
writer.WriteLine(" output.WriteEnum({0}, field_names[{2}], (int) {1}, {1});", Number, PropertyName, FieldOrdinal); writer.WriteLine(" output.WriteEnum({0}, field_names[{2}], (int) {1}, {1});", Number, PropertyName,
FieldOrdinal);
writer.WriteLine("}"); writer.WriteLine("}");
} }
......
...@@ -48,7 +48,8 @@ namespace Google.ProtocolBuffers.ProtoGen ...@@ -48,7 +48,8 @@ namespace Google.ProtocolBuffers.ProtoGen
public void Generate(TextGenerator writer) public void Generate(TextGenerator writer)
{ {
writer.WriteLine("[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]"); writer.WriteLine("[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]");
writer.WriteLine("[global::System.CodeDom.Compiler.GeneratedCodeAttribute(\"{0}\", \"{1}\")]", GetType().Assembly.GetName().Name, GetType().Assembly.GetName().Version); writer.WriteLine("[global::System.CodeDom.Compiler.GeneratedCodeAttribute(\"{0}\", \"{1}\")]",
GetType().Assembly.GetName().Name, GetType().Assembly.GetName().Version);
writer.WriteLine("{0} enum {1} {{", ClassAccessLevel, Descriptor.Name); writer.WriteLine("{0} enum {1} {{", ClassAccessLevel, Descriptor.Name);
writer.Indent(); writer.Indent();
foreach (EnumValueDescriptor value in Descriptor.Values) foreach (EnumValueDescriptor value in Descriptor.Values)
......
...@@ -35,7 +35,6 @@ ...@@ -35,7 +35,6 @@
#endregion #endregion
using System; using System;
using System.Globalization;
using Google.ProtocolBuffers.Descriptors; using Google.ProtocolBuffers.Descriptors;
namespace Google.ProtocolBuffers.ProtoGen namespace Google.ProtocolBuffers.ProtoGen
...@@ -124,10 +123,12 @@ namespace Google.ProtocolBuffers.ProtoGen ...@@ -124,10 +123,12 @@ namespace Google.ProtocolBuffers.ProtoGen
writer.WriteLine("\"{0}\",", Descriptor.FullName); writer.WriteLine("\"{0}\",", Descriptor.FullName);
writer.WriteLine("{0}.DefaultInstance,", extends); writer.WriteLine("{0}.DefaultInstance,", extends);
if (!Descriptor.IsRepeated) if (!Descriptor.IsRepeated)
{
writer.WriteLine("{0},", writer.WriteLine("{0},",
Descriptor.HasDefaultValue Descriptor.HasDefaultValue
? DefaultValue ? DefaultValue
: IsNullableType ? "null" : "default(" + type + ")"); : IsNullableType ? "null" : "default(" + type + ")");
}
writer.WriteLine("{0},", writer.WriteLine("{0},",
(Descriptor.MappedType == MappedType.Message) ? type + ".DefaultInstance" : "null"); (Descriptor.MappedType == MappedType.Message) ? type + ".DefaultInstance" : "null");
writer.WriteLine("{0},", writer.WriteLine("{0},",
......
...@@ -36,6 +36,7 @@ ...@@ -36,6 +36,7 @@
using System; using System;
using System.Globalization; using System.Globalization;
using System.Text;
using Google.ProtocolBuffers.Descriptors; using Google.ProtocolBuffers.Descriptors;
namespace Google.ProtocolBuffers.ProtoGen namespace Google.ProtocolBuffers.ProtoGen
...@@ -54,7 +55,10 @@ namespace Google.ProtocolBuffers.ProtoGen ...@@ -54,7 +55,10 @@ namespace Google.ProtocolBuffers.ProtoGen
public abstract void WriteEquals(TextGenerator writer); public abstract void WriteEquals(TextGenerator writer);
public abstract void WriteToString(TextGenerator writer); public abstract void WriteToString(TextGenerator writer);
public int FieldOrdinal { get { return _fieldOrdinal; } } public int FieldOrdinal
{
get { return _fieldOrdinal; }
}
private static bool AllPrintableAscii(string text) private static bool AllPrintableAscii(string text)
{ {
...@@ -141,21 +145,33 @@ namespace Google.ProtocolBuffers.ProtoGen ...@@ -141,21 +145,33 @@ namespace Google.ProtocolBuffers.ProtoGen
if (Descriptor.FieldType == FieldType.Double && value is double) if (Descriptor.FieldType == FieldType.Double && value is double)
{ {
if (double.IsNaN((double) value)) if (double.IsNaN((double) value))
{
return "double.NaN"; return "double.NaN";
}
if (double.IsPositiveInfinity((double) value)) if (double.IsPositiveInfinity((double) value))
{
return "double.PositiveInfinity"; return "double.PositiveInfinity";
}
if (double.IsNegativeInfinity((double) value)) if (double.IsNegativeInfinity((double) value))
{
return "double.NegativeInfinity"; return "double.NegativeInfinity";
} }
}
else if (Descriptor.FieldType == FieldType.Float && value is float) else if (Descriptor.FieldType == FieldType.Float && value is float)
{ {
if (float.IsNaN((float) value)) if (float.IsNaN((float) value))
{
return "float.NaN"; return "float.NaN";
}
if (float.IsPositiveInfinity((float) value)) if (float.IsPositiveInfinity((float) value))
{
return "float.PositiveInfinity"; return "float.PositiveInfinity";
}
if (float.IsNegativeInfinity((float) value)) if (float.IsNegativeInfinity((float) value))
{
return "float.NegativeInfinity"; return "float.NegativeInfinity";
} }
}
return value.ToString(CultureInfo.InvariantCulture) + suffix; return value.ToString(CultureInfo.InvariantCulture) + suffix;
} }
case FieldType.Bool: case FieldType.Bool:
...@@ -188,7 +204,7 @@ namespace Google.ProtocolBuffers.ProtoGen ...@@ -188,7 +204,7 @@ namespace Google.ProtocolBuffers.ProtoGen
{ {
string temp = string temp =
Convert.ToBase64String( Convert.ToBase64String(
System.Text.Encoding.UTF8.GetBytes((String) Descriptor.DefaultValue)); Encoding.UTF8.GetBytes((String) Descriptor.DefaultValue));
return String.Format("ByteString.FromBase64(\"{0}\").ToStringUtf8()", temp); return String.Format("ByteString.FromBase64(\"{0}\").ToStringUtf8()", temp);
} }
return string.Format("(string) {0}.Descriptor.Fields[{1}].DefaultValue", return string.Format("(string) {0}.Descriptor.Fields[{1}].DefaultValue",
......
...@@ -35,11 +35,11 @@ ...@@ -35,11 +35,11 @@
#endregion #endregion
using System.Collections.Generic; using System.Collections.Generic;
using System.IO;
using System.Text; using System.Text;
using Google.ProtocolBuffers.Collections;
using Google.ProtocolBuffers.DescriptorProtos; using Google.ProtocolBuffers.DescriptorProtos;
using System.IO;
using Google.ProtocolBuffers.Descriptors; using Google.ProtocolBuffers.Descriptors;
using Google.ProtocolBuffers.Collections;
namespace Google.ProtocolBuffers.ProtoGen namespace Google.ProtocolBuffers.ProtoGen
{ {
...@@ -148,7 +148,9 @@ namespace Google.ProtocolBuffers.ProtoGen ...@@ -148,7 +148,9 @@ namespace Google.ProtocolBuffers.ProtoGen
// we've already converted all the dependencies, until we get to a stalemate // we've already converted all the dependencies, until we get to a stalemate
List<FileDescriptorProto> fileList = new List<FileDescriptorProto>(); List<FileDescriptorProto> fileList = new List<FileDescriptorProto>();
foreach (FileDescriptorSet set in descriptorProtos) foreach (FileDescriptorSet set in descriptorProtos)
{
fileList.AddRange(set.FileList); fileList.AddRange(set.FileList);
}
FileDescriptor[] converted = new FileDescriptor[fileList.Count]; FileDescriptor[] converted = new FileDescriptor[fileList.Count];
...@@ -172,10 +174,10 @@ namespace Google.ProtocolBuffers.ProtoGen ...@@ -172,10 +174,10 @@ namespace Google.ProtocolBuffers.ProtoGen
CSharpFileOptions.Builder builder = options.ToBuilder(); CSharpFileOptions.Builder builder = options.ToBuilder();
if (candidate.Options.HasExtension(DescriptorProtos.CSharpOptions.CSharpFileOptions)) if (candidate.Options.HasExtension(CSharpOptions.CSharpFileOptions))
{ {
builder.MergeFrom( builder.MergeFrom(
candidate.Options.GetExtension(DescriptorProtos.CSharpOptions.CSharpFileOptions)); candidate.Options.GetExtension(CSharpOptions.CSharpFileOptions));
} }
CSharpFileOptions localOptions = builder.Build(); CSharpFileOptions localOptions = builder.Build();
......
...@@ -129,7 +129,8 @@ namespace Google.ProtocolBuffers.ProtoGen ...@@ -129,7 +129,8 @@ namespace Google.ProtocolBuffers.ProtoGen
public void GenerateSerializationCode(TextGenerator writer) public void GenerateSerializationCode(TextGenerator writer)
{ {
writer.WriteLine("if (has{0}) {{", PropertyName); writer.WriteLine("if (has{0}) {{", PropertyName);
writer.WriteLine(" output.Write{0}({1}, field_names[{3}], {2});", MessageOrGroup, Number, PropertyName, FieldOrdinal); writer.WriteLine(" output.Write{0}({1}, field_names[{3}], {2});", MessageOrGroup, Number, PropertyName,
FieldOrdinal);
writer.WriteLine("}"); writer.WriteLine("}");
} }
......
...@@ -38,7 +38,6 @@ using System; ...@@ -38,7 +38,6 @@ using System;
using System.Collections.Generic; using System.Collections.Generic;
using Google.ProtocolBuffers.DescriptorProtos; using Google.ProtocolBuffers.DescriptorProtos;
using Google.ProtocolBuffers.Descriptors; using Google.ProtocolBuffers.Descriptors;
using ExtensionRange = Google.ProtocolBuffers.DescriptorProtos.DescriptorProto.Types.ExtensionRange;
namespace Google.ProtocolBuffers.ProtoGen namespace Google.ProtocolBuffers.ProtoGen
{ {
...@@ -146,7 +145,9 @@ namespace Google.ProtocolBuffers.ProtoGen ...@@ -146,7 +145,9 @@ namespace Google.ProtocolBuffers.ProtoGen
{ {
List<string> names = new List<string>(); List<string> names = new List<string>();
foreach (FieldDescriptor fieldDescriptor in Descriptor.Fields) foreach (FieldDescriptor fieldDescriptor in Descriptor.Fields)
{
names.Add(fieldDescriptor.Name); names.Add(fieldDescriptor.Name);
}
//if you change this, the search must also change in GenerateBuilderParsingMethods //if you change this, the search must also change in GenerateBuilderParsingMethods
names.Sort(StringComparer.Ordinal); names.Sort(StringComparer.Ordinal);
_fieldNames = names.ToArray(); _fieldNames = names.ToArray();
...@@ -169,7 +170,8 @@ namespace Google.ProtocolBuffers.ProtoGen ...@@ -169,7 +170,8 @@ namespace Google.ProtocolBuffers.ProtoGen
{ {
writer.WriteLine("[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]"); writer.WriteLine("[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]");
writer.WriteLine("[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]"); writer.WriteLine("[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]");
writer.WriteLine("[global::System.CodeDom.Compiler.GeneratedCodeAttribute(\"{0}\", \"{1}\")]", GetType().Assembly.GetName().Name, GetType().Assembly.GetName().Version); writer.WriteLine("[global::System.CodeDom.Compiler.GeneratedCodeAttribute(\"{0}\", \"{1}\")]",
GetType().Assembly.GetName().Name, GetType().Assembly.GetName().Version);
writer.WriteLine("{0} sealed partial class {1} : pb::{2}Message{3}<{1}, {1}.Builder> {{", writer.WriteLine("{0} sealed partial class {1} : pb::{2}Message{3}<{1}, {1}.Builder> {{",
ClassAccessLevel, ClassName, ClassAccessLevel, ClassName,
Descriptor.Proto.ExtensionRangeCount > 0 ? "Extendable" : "Generated", Descriptor.Proto.ExtensionRangeCount > 0 ? "Extendable" : "Generated",
...@@ -181,10 +183,13 @@ namespace Google.ProtocolBuffers.ProtoGen ...@@ -181,10 +183,13 @@ namespace Google.ProtocolBuffers.ProtoGen
if (OptimizeSpeed) if (OptimizeSpeed)
{ {
writer.WriteLine("private static readonly string[] _{0}FieldNames = new string[] {{ {2}{1}{2} }};", writer.WriteLine("private static readonly string[] _{0}FieldNames = new string[] {{ {2}{1}{2} }};",
NameHelpers.UnderscoresToCamelCase(ClassName), String.Join("\", \"", FieldNames), FieldNames.Length > 0 ? "\"" : ""); NameHelpers.UnderscoresToCamelCase(ClassName), String.Join("\", \"", FieldNames),
FieldNames.Length > 0 ? "\"" : "");
List<string> tags = new List<string>(); List<string> tags = new List<string>();
foreach (string name in FieldNames) foreach (string name in FieldNames)
{
tags.Add(WireFormat.MakeTag(Descriptor.FindFieldByName(name)).ToString()); tags.Add(WireFormat.MakeTag(Descriptor.FindFieldByName(name)).ToString());
}
writer.WriteLine("private static readonly uint[] _{0}FieldTags = new uint[] {{ {1} }};", writer.WriteLine("private static readonly uint[] _{0}FieldTags = new uint[] {{ {1} }};",
NameHelpers.UnderscoresToCamelCase(ClassName), String.Join(", ", tags.ToArray())); NameHelpers.UnderscoresToCamelCase(ClassName), String.Join(", ", tags.ToArray()));
...@@ -227,7 +232,8 @@ namespace Google.ProtocolBuffers.ProtoGen ...@@ -227,7 +232,8 @@ namespace Google.ProtocolBuffers.ProtoGen
writer.WriteLine("#region Nested types"); writer.WriteLine("#region Nested types");
writer.WriteLine("[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]"); writer.WriteLine("[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]");
writer.WriteLine("[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]"); writer.WriteLine("[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]");
writer.WriteLine("[global::System.CodeDom.Compiler.GeneratedCodeAttribute(\"{0}\", \"{1}\")]", GetType().Assembly.GetName().Name, GetType().Assembly.GetName().Version); writer.WriteLine("[global::System.CodeDom.Compiler.GeneratedCodeAttribute(\"{0}\", \"{1}\")]",
GetType().Assembly.GetName().Name, GetType().Assembly.GetName().Version);
writer.WriteLine("public static class Types {"); writer.WriteLine("public static class Types {");
writer.Indent(); writer.Indent();
WriteChildren(writer, null, Descriptor.EnumTypes); WriteChildren(writer, null, Descriptor.EnumTypes);
...@@ -287,7 +293,10 @@ namespace Google.ProtocolBuffers.ProtoGen ...@@ -287,7 +293,10 @@ namespace Google.ProtocolBuffers.ProtoGen
{ {
CreateFieldGenerator(fieldDescriptor).WriteHash(writer); CreateFieldGenerator(fieldDescriptor).WriteHash(writer);
} }
if (callbase) writer.WriteLine("hash ^= base.GetHashCode();"); if (callbase)
{
writer.WriteLine("hash ^= base.GetHashCode();");
}
writer.WriteLine("return hash;"); writer.WriteLine("return hash;");
writer.Outdent(); writer.Outdent();
writer.WriteLine("}"); writer.WriteLine("}");
...@@ -301,7 +310,10 @@ namespace Google.ProtocolBuffers.ProtoGen ...@@ -301,7 +310,10 @@ namespace Google.ProtocolBuffers.ProtoGen
{ {
CreateFieldGenerator(fieldDescriptor).WriteEquals(writer); CreateFieldGenerator(fieldDescriptor).WriteEquals(writer);
} }
if (callbase) writer.WriteLine("if (!base.Equals(other)) return false;"); if (callbase)
{
writer.WriteLine("if (!base.Equals(other)) return false;");
}
writer.WriteLine("return true;"); writer.WriteLine("return true;");
writer.Outdent(); writer.Outdent();
writer.WriteLine("}"); writer.WriteLine("}");
...@@ -317,7 +329,10 @@ namespace Google.ProtocolBuffers.ProtoGen ...@@ -317,7 +329,10 @@ namespace Google.ProtocolBuffers.ProtoGen
{ {
CreateFieldGenerator(fieldDescriptor).WriteToString(writer); CreateFieldGenerator(fieldDescriptor).WriteToString(writer);
} }
if (callbase) writer.WriteLine("base.PrintTo(writer);"); if (callbase)
{
writer.WriteLine("base.PrintTo(writer);");
}
writer.Outdent(); writer.Outdent();
writer.WriteLine("}"); writer.WriteLine("}");
writer.WriteLine("#endregion"); writer.WriteLine("#endregion");
...@@ -329,7 +344,8 @@ namespace Google.ProtocolBuffers.ProtoGen ...@@ -329,7 +344,8 @@ namespace Google.ProtocolBuffers.ProtoGen
List<FieldDescriptor> sortedFields = new List<FieldDescriptor>(Descriptor.Fields); List<FieldDescriptor> sortedFields = new List<FieldDescriptor>(Descriptor.Fields);
sortedFields.Sort((f1, f2) => f1.FieldNumber.CompareTo(f2.FieldNumber)); sortedFields.Sort((f1, f2) => f1.FieldNumber.CompareTo(f2.FieldNumber));
List<ExtensionRange> sortedExtensions = new List<ExtensionRange>(Descriptor.Proto.ExtensionRangeList); List<DescriptorProto.Types.ExtensionRange> sortedExtensions =
new List<DescriptorProto.Types.ExtensionRange>(Descriptor.Proto.ExtensionRangeList);
sortedExtensions.Sort((r1, r2) => (r1.Start.CompareTo(r2.Start))); sortedExtensions.Sort((r1, r2) => (r1.Start.CompareTo(r2.Start)));
writer.WriteLine("public override void WriteTo(pb::ICodedOutputStream output) {"); writer.WriteLine("public override void WriteTo(pb::ICodedOutputStream output) {");
...@@ -423,7 +439,8 @@ namespace Google.ProtocolBuffers.ProtoGen ...@@ -423,7 +439,8 @@ namespace Google.ProtocolBuffers.ProtoGen
CreateFieldGenerator(fieldDescriptor).GenerateSerializationCode(writer); CreateFieldGenerator(fieldDescriptor).GenerateSerializationCode(writer);
} }
private static void GenerateSerializeOneExtensionRange(TextGenerator writer, ExtensionRange extensionRange) private static void GenerateSerializeOneExtensionRange(TextGenerator writer,
DescriptorProto.Types.ExtensionRange extensionRange)
{ {
writer.WriteLine("extensionWriter.WriteUntil({0}, output);", extensionRange.End); writer.WriteLine("extensionWriter.WriteUntil({0}, output);", extensionRange.End);
} }
...@@ -534,7 +551,8 @@ namespace Google.ProtocolBuffers.ProtoGen ...@@ -534,7 +551,8 @@ namespace Google.ProtocolBuffers.ProtoGen
writer.WriteLine(); writer.WriteLine();
writer.WriteLine("[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]"); writer.WriteLine("[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]");
writer.WriteLine("[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]"); writer.WriteLine("[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]");
writer.WriteLine("[global::System.CodeDom.Compiler.GeneratedCodeAttribute(\"{0}\", \"{1}\")]", GetType().Assembly.GetName().Name, GetType().Assembly.GetName().Version); writer.WriteLine("[global::System.CodeDom.Compiler.GeneratedCodeAttribute(\"{0}\", \"{1}\")]",
GetType().Assembly.GetName().Name, GetType().Assembly.GetName().Version);
writer.WriteLine("{0} sealed partial class Builder : pb::{2}Builder{3}<{1}, Builder> {{", writer.WriteLine("{0} sealed partial class Builder : pb::{2}Builder{3}<{1}, Builder> {{",
ClassAccessLevel, ClassName, ClassAccessLevel, ClassName,
Descriptor.Proto.ExtensionRangeCount > 0 ? "Extendable" : "Generated", RuntimeSuffix); Descriptor.Proto.ExtensionRangeCount > 0 ? "Extendable" : "Generated", RuntimeSuffix);
...@@ -664,7 +682,8 @@ namespace Google.ProtocolBuffers.ProtoGen ...@@ -664,7 +682,8 @@ namespace Google.ProtocolBuffers.ProtoGen
writer.WriteLine("if(tag == 0 && field_name != null) {"); writer.WriteLine("if(tag == 0 && field_name != null) {");
writer.Indent(); writer.Indent();
//if you change from StringComparer.Ordinal, the array sort in FieldNames { get; } must also change //if you change from StringComparer.Ordinal, the array sort in FieldNames { get; } must also change
writer.WriteLine("int field_ordinal = global::System.Array.BinarySearch(_{0}FieldNames, field_name, global::System.StringComparer.Ordinal);", writer.WriteLine(
"int field_ordinal = global::System.Array.BinarySearch(_{0}FieldNames, field_name, global::System.StringComparer.Ordinal);",
NameHelpers.UnderscoresToCamelCase(ClassName)); NameHelpers.UnderscoresToCamelCase(ClassName));
writer.WriteLine("if(field_ordinal >= 0)"); writer.WriteLine("if(field_ordinal >= 0)");
writer.WriteLine(" tag = _{0}FieldTags[field_ordinal];", NameHelpers.UnderscoresToCamelCase(ClassName)); writer.WriteLine(" tag = _{0}FieldTags[field_ordinal];", NameHelpers.UnderscoresToCamelCase(ClassName));
...@@ -675,7 +694,8 @@ namespace Google.ProtocolBuffers.ProtoGen ...@@ -675,7 +694,8 @@ namespace Google.ProtocolBuffers.ProtoGen
writer.WriteLine(" unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields);"); writer.WriteLine(" unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields);");
writer.WriteLine(" }"); writer.WriteLine(" }");
} }
writer.WriteLine(" ParseUnknownField(input, {0}extensionRegistry, tag, field_name);", UseLiteRuntime ? "" : "unknownFields, "); writer.WriteLine(" ParseUnknownField(input, {0}extensionRegistry, tag, field_name);",
UseLiteRuntime ? "" : "unknownFields, ");
writer.WriteLine(" continue;"); writer.WriteLine(" continue;");
writer.WriteLine("}"); writer.WriteLine("}");
writer.Outdent(); writer.Outdent();
...@@ -718,8 +738,13 @@ namespace Google.ProtocolBuffers.ProtoGen ...@@ -718,8 +738,13 @@ namespace Google.ProtocolBuffers.ProtoGen
WireFormat.WireType wt = WireFormat.GetWireType(field.FieldType); WireFormat.WireType wt = WireFormat.GetWireType(field.FieldType);
uint tag = WireFormat.MakeTag(field.FieldNumber, wt); uint tag = WireFormat.MakeTag(field.FieldNumber, wt);
if(field.IsRepeated && (wt == WireFormat.WireType.Varint || wt == WireFormat.WireType.Fixed32 || wt == WireFormat.WireType.Fixed64)) if (field.IsRepeated &&
writer.WriteLine("case {0}:", WireFormat.MakeTag(field.FieldNumber, WireFormat.WireType.LengthDelimited)); (wt == WireFormat.WireType.Varint || wt == WireFormat.WireType.Fixed32 ||
wt == WireFormat.WireType.Fixed64))
{
writer.WriteLine("case {0}:",
WireFormat.MakeTag(field.FieldNumber, WireFormat.WireType.LengthDelimited));
}
writer.WriteLine("case {0}: {{", tag); writer.WriteLine("case {0}: {{", tag);
writer.Indent(); writer.Indent();
......
...@@ -103,7 +103,8 @@ namespace Google.ProtocolBuffers.ProtoGen ...@@ -103,7 +103,8 @@ namespace Google.ProtocolBuffers.ProtoGen
public void GenerateSerializationCode(TextGenerator writer) public void GenerateSerializationCode(TextGenerator writer)
{ {
writer.WriteLine("if (has{0}) {{", PropertyName); writer.WriteLine("if (has{0}) {{", PropertyName);
writer.WriteLine(" output.Write{0}({1}, field_names[{3}], {2});", CapitalizedTypeName, Number, PropertyName, FieldOrdinal); writer.WriteLine(" output.Write{0}({1}, field_names[{3}], {2});", CapitalizedTypeName, Number, PropertyName,
FieldOrdinal);
writer.WriteLine("}"); writer.WriteLine("}");
} }
......
...@@ -14,8 +14,8 @@ namespace Google.ProtocolBuffers.ProtoGen ...@@ -14,8 +14,8 @@ namespace Google.ProtocolBuffers.ProtoGen
/// </summary> /// </summary>
public class ProgramPreprocess public class ProgramPreprocess
{ {
const string ProtocExecutable = "protoc.exe"; private const string ProtocExecutable = "protoc.exe";
const string ProtocDirectoryArg = "--protoc_dir="; private const string ProtocDirectoryArg = "--protoc_dir=";
private static int Main(string[] args) private static int Main(string[] args)
{ {
......
using System.Reflection; using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following // General Information about an assembly is controlled through the following
......
...@@ -34,7 +34,6 @@ ...@@ -34,7 +34,6 @@
#endregion #endregion
using Google.ProtocolBuffers.DescriptorProtos;
using Google.ProtocolBuffers.Descriptors; using Google.ProtocolBuffers.Descriptors;
namespace Google.ProtocolBuffers.ProtoGen namespace Google.ProtocolBuffers.ProtoGen
...@@ -132,9 +131,16 @@ namespace Google.ProtocolBuffers.ProtoGen ...@@ -132,9 +131,16 @@ namespace Google.ProtocolBuffers.ProtoGen
writer.WriteLine("if ({0}_.Count > 0) {{", Name); writer.WriteLine("if ({0}_.Count > 0) {{", Name);
writer.Indent(); writer.Indent();
if (Descriptor.IsPacked) if (Descriptor.IsPacked)
writer.WriteLine("output.WritePackedEnumArray({0}, field_names[{2}], {1}MemoizedSerializedSize, {1}_);", Number, Name, FieldOrdinal, Descriptor.FieldType); {
writer.WriteLine(
"output.WritePackedEnumArray({0}, field_names[{2}], {1}MemoizedSerializedSize, {1}_);", Number, Name,
FieldOrdinal, Descriptor.FieldType);
}
else else
writer.WriteLine("output.WriteEnumArray({0}, field_names[{2}], {1}_);", Number, Name, FieldOrdinal, Descriptor.FieldType); {
writer.WriteLine("output.WriteEnumArray({0}, field_names[{2}], {1}_);", Number, Name, FieldOrdinal,
Descriptor.FieldType);
}
writer.Outdent(); writer.Outdent();
writer.WriteLine("}"); writer.WriteLine("}");
} }
......
...@@ -34,7 +34,6 @@ ...@@ -34,7 +34,6 @@
#endregion #endregion
using System;
using Google.ProtocolBuffers.Descriptors; using Google.ProtocolBuffers.Descriptors;
namespace Google.ProtocolBuffers.ProtoGen namespace Google.ProtocolBuffers.ProtoGen
...@@ -122,14 +121,17 @@ namespace Google.ProtocolBuffers.ProtoGen ...@@ -122,14 +121,17 @@ namespace Google.ProtocolBuffers.ProtoGen
public void GenerateParsingCode(TextGenerator writer) public void GenerateParsingCode(TextGenerator writer)
{ {
writer.WriteLine("input.Read{0}Array(tag, field_name, result.{1}_, {2}.DefaultInstance, extensionRegistry);", MessageOrGroup, Name, TypeName); writer.WriteLine(
"input.Read{0}Array(tag, field_name, result.{1}_, {2}.DefaultInstance, extensionRegistry);",
MessageOrGroup, Name, TypeName);
} }
public void GenerateSerializationCode(TextGenerator writer) public void GenerateSerializationCode(TextGenerator writer)
{ {
writer.WriteLine("if ({0}_.Count > 0) {{", Name); writer.WriteLine("if ({0}_.Count > 0) {{", Name);
writer.Indent(); writer.Indent();
writer.WriteLine("output.Write{0}Array({1}, field_names[{3}], {2}_);", MessageOrGroup, Number, Name, FieldOrdinal, Descriptor.FieldType); writer.WriteLine("output.Write{0}Array({1}, field_names[{3}], {2}_);", MessageOrGroup, Number, Name,
FieldOrdinal, Descriptor.FieldType);
writer.Outdent(); writer.Outdent();
writer.WriteLine("}"); writer.WriteLine("}");
} }
......
...@@ -34,7 +34,6 @@ ...@@ -34,7 +34,6 @@
#endregion #endregion
using Google.ProtocolBuffers.DescriptorProtos;
using Google.ProtocolBuffers.Descriptors; using Google.ProtocolBuffers.Descriptors;
namespace Google.ProtocolBuffers.ProtoGen namespace Google.ProtocolBuffers.ProtoGen
...@@ -121,7 +120,8 @@ namespace Google.ProtocolBuffers.ProtoGen ...@@ -121,7 +120,8 @@ namespace Google.ProtocolBuffers.ProtoGen
public void GenerateParsingCode(TextGenerator writer) public void GenerateParsingCode(TextGenerator writer)
{ {
writer.WriteLine("input.Read{0}Array(tag, field_name, result.{1}_);", CapitalizedTypeName, Name, Descriptor.FieldType); writer.WriteLine("input.Read{0}Array(tag, field_name, result.{1}_);", CapitalizedTypeName, Name,
Descriptor.FieldType);
} }
public void GenerateSerializationCode(TextGenerator writer) public void GenerateSerializationCode(TextGenerator writer)
...@@ -129,9 +129,15 @@ namespace Google.ProtocolBuffers.ProtoGen ...@@ -129,9 +129,15 @@ namespace Google.ProtocolBuffers.ProtoGen
writer.WriteLine("if ({0}_.Count > 0) {{", Name); writer.WriteLine("if ({0}_.Count > 0) {{", Name);
writer.Indent(); writer.Indent();
if (Descriptor.IsPacked) if (Descriptor.IsPacked)
writer.WriteLine("output.WritePacked{0}Array({1}, field_names[{3}], {2}MemoizedSerializedSize, {2}_);", CapitalizedTypeName, Number, Name, FieldOrdinal, Descriptor.FieldType); {
writer.WriteLine("output.WritePacked{0}Array({1}, field_names[{3}], {2}MemoizedSerializedSize, {2}_);",
CapitalizedTypeName, Number, Name, FieldOrdinal, Descriptor.FieldType);
}
else else
writer.WriteLine("output.Write{0}Array({1}, field_names[{3}], {2}_);", CapitalizedTypeName, Number, Name, FieldOrdinal, Descriptor.FieldType); {
writer.WriteLine("output.Write{0}Array({1}, field_names[{3}], {2}_);", CapitalizedTypeName, Number, Name,
FieldOrdinal, Descriptor.FieldType);
}
writer.Outdent(); writer.Outdent();
writer.WriteLine("}"); writer.WriteLine("}");
} }
......
...@@ -55,7 +55,8 @@ namespace Google.ProtocolBuffers.ProtoGen ...@@ -55,7 +55,8 @@ namespace Google.ProtocolBuffers.ProtoGen
{ {
writer.WriteLine("[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]"); writer.WriteLine("[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]");
writer.WriteLine("[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]"); writer.WriteLine("[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]");
writer.WriteLine("[global::System.CodeDom.Compiler.GeneratedCodeAttribute(\"{0}\", \"{1}\")]", GetType().Assembly.GetName().Name, GetType().Assembly.GetName().Version); writer.WriteLine("[global::System.CodeDom.Compiler.GeneratedCodeAttribute(\"{0}\", \"{1}\")]",
GetType().Assembly.GetName().Name, GetType().Assembly.GetName().Version);
writer.WriteLine("{0} abstract class {1} : pb::IService {{", ClassAccessLevel, Descriptor.Name); writer.WriteLine("{0} abstract class {1} : pb::IService {{", ClassAccessLevel, Descriptor.Name);
writer.Indent(); writer.Indent();
...@@ -156,7 +157,8 @@ namespace Google.ProtocolBuffers.ProtoGen ...@@ -156,7 +157,8 @@ namespace Google.ProtocolBuffers.ProtoGen
writer.WriteLine(); writer.WriteLine();
writer.WriteLine("[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]"); writer.WriteLine("[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]");
writer.WriteLine("[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]"); writer.WriteLine("[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]");
writer.WriteLine("[global::System.CodeDom.Compiler.GeneratedCodeAttribute(\"{0}\", \"{1}\")]", GetType().Assembly.GetName().Name, GetType().Assembly.GetName().Version); writer.WriteLine("[global::System.CodeDom.Compiler.GeneratedCodeAttribute(\"{0}\", \"{1}\")]",
GetType().Assembly.GetName().Name, GetType().Assembly.GetName().Version);
writer.WriteLine("{0} class Stub : {1} {{", ClassAccessLevel, GetClassName(Descriptor)); writer.WriteLine("{0} class Stub : {1} {{", ClassAccessLevel, GetClassName(Descriptor));
writer.Indent(); writer.Indent();
writer.WriteLine("internal Stub(pb::IRpcChannel channel) {"); writer.WriteLine("internal Stub(pb::IRpcChannel channel) {");
......
...@@ -35,7 +35,6 @@ ...@@ -35,7 +35,6 @@
#endregion #endregion
using System; using System;
using System.Collections.Generic;
using Google.ProtocolBuffers.DescriptorProtos; using Google.ProtocolBuffers.DescriptorProtos;
using Google.ProtocolBuffers.Descriptors; using Google.ProtocolBuffers.Descriptors;
...@@ -106,7 +105,8 @@ namespace Google.ProtocolBuffers.ProtoGen ...@@ -106,7 +105,8 @@ namespace Google.ProtocolBuffers.ProtoGen
new Guid(options.InterfaceId)); new Guid(options.InterfaceId));
} }
writer.WriteLine("[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]"); writer.WriteLine("[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]");
writer.WriteLine("[global::System.CodeDom.Compiler.GeneratedCodeAttribute(\"{0}\", \"{1}\")]", GetType().Assembly.GetName().Name, GetType().Assembly.GetName().Version); writer.WriteLine("[global::System.CodeDom.Compiler.GeneratedCodeAttribute(\"{0}\", \"{1}\")]",
GetType().Assembly.GetName().Name, GetType().Assembly.GetName().Version);
writer.WriteLine("{0} partial interface I{1} {{", ClassAccessLevel, Descriptor.Name); writer.WriteLine("{0} partial interface I{1} {{", ClassAccessLevel, Descriptor.Name);
writer.Indent(); writer.Indent();
...@@ -143,10 +143,13 @@ namespace Google.ProtocolBuffers.ProtoGen ...@@ -143,10 +143,13 @@ namespace Google.ProtocolBuffers.ProtoGen
// CLIENT Proxy // CLIENT Proxy
{ {
if (Descriptor.File.CSharpOptions.ClsCompliance) if (Descriptor.File.CSharpOptions.ClsCompliance)
{
writer.WriteLine("[global::System.CLSCompliant(false)]"); writer.WriteLine("[global::System.CLSCompliant(false)]");
}
writer.WriteLine("[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]"); writer.WriteLine("[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]");
writer.WriteLine("[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]"); writer.WriteLine("[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]");
writer.WriteLine("[global::System.CodeDom.Compiler.GeneratedCodeAttribute(\"{0}\", \"{1}\")]", GetType().Assembly.GetName().Name, GetType().Assembly.GetName().Version); writer.WriteLine("[global::System.CodeDom.Compiler.GeneratedCodeAttribute(\"{0}\", \"{1}\")]",
GetType().Assembly.GetName().Name, GetType().Assembly.GetName().Version);
writer.WriteLine("{0} partial class {1} : I{1}, pb::IRpcDispatch, global::System.IDisposable {{", writer.WriteLine("{0} partial class {1} : I{1}, pb::IRpcDispatch, global::System.IDisposable {{",
ClassAccessLevel, Descriptor.Name); ClassAccessLevel, Descriptor.Name);
writer.Indent(); writer.Indent();
...@@ -190,10 +193,13 @@ namespace Google.ProtocolBuffers.ProtoGen ...@@ -190,10 +193,13 @@ namespace Google.ProtocolBuffers.ProtoGen
// SERVER - DISPATCH // SERVER - DISPATCH
{ {
if (Descriptor.File.CSharpOptions.ClsCompliance) if (Descriptor.File.CSharpOptions.ClsCompliance)
{
writer.WriteLine("[global::System.CLSCompliant(false)]"); writer.WriteLine("[global::System.CLSCompliant(false)]");
}
writer.WriteLine("[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]"); writer.WriteLine("[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]");
writer.WriteLine("[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]"); writer.WriteLine("[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]");
writer.WriteLine("[global::System.CodeDom.Compiler.GeneratedCodeAttribute(\"{0}\", \"{1}\")]", GetType().Assembly.GetName().Name, GetType().Assembly.GetName().Version); writer.WriteLine("[global::System.CodeDom.Compiler.GeneratedCodeAttribute(\"{0}\", \"{1}\")]",
GetType().Assembly.GetName().Name, GetType().Assembly.GetName().Version);
writer.WriteLine("public partial class Dispatch : pb::IRpcDispatch, global::System.IDisposable {"); writer.WriteLine("public partial class Dispatch : pb::IRpcDispatch, global::System.IDisposable {");
writer.Indent(); writer.Indent();
writer.WriteLine("private readonly bool dispose;"); writer.WriteLine("private readonly bool dispose;");
...@@ -230,7 +236,8 @@ namespace Google.ProtocolBuffers.ProtoGen ...@@ -230,7 +236,8 @@ namespace Google.ProtocolBuffers.ProtoGen
GetClassName(method.InputType)); GetClassName(method.InputType));
} }
writer.WriteLine( writer.WriteLine(
"default: throw new global::System.MissingMethodException(typeof(I{0}).FullName, methodName);", Descriptor.Name); "default: throw new global::System.MissingMethodException(typeof(I{0}).FullName, methodName);",
Descriptor.Name);
writer.Outdent(); writer.Outdent();
writer.WriteLine("}"); //end switch writer.WriteLine("}"); //end switch
writer.Outdent(); writer.Outdent();
...@@ -241,10 +248,13 @@ namespace Google.ProtocolBuffers.ProtoGen ...@@ -241,10 +248,13 @@ namespace Google.ProtocolBuffers.ProtoGen
// SERVER - STUB // SERVER - STUB
{ {
if (Descriptor.File.CSharpOptions.ClsCompliance) if (Descriptor.File.CSharpOptions.ClsCompliance)
{
writer.WriteLine("[global::System.CLSCompliant(false)]"); writer.WriteLine("[global::System.CLSCompliant(false)]");
}
writer.WriteLine("[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]"); writer.WriteLine("[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]");
writer.WriteLine("[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]"); writer.WriteLine("[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]");
writer.WriteLine("[global::System.CodeDom.Compiler.GeneratedCodeAttribute(\"{0}\", \"{1}\")]", GetType().Assembly.GetName().Name, GetType().Assembly.GetName().Version); writer.WriteLine("[global::System.CodeDom.Compiler.GeneratedCodeAttribute(\"{0}\", \"{1}\")]",
GetType().Assembly.GetName().Name, GetType().Assembly.GetName().Version);
writer.WriteLine( writer.WriteLine(
"public partial class ServerStub : pb::IRpcServerStub, global::System.IDisposable {"); "public partial class ServerStub : pb::IRpcServerStub, global::System.IDisposable {");
writer.Indent(); writer.Indent();
...@@ -287,7 +297,8 @@ namespace Google.ProtocolBuffers.ProtoGen ...@@ -287,7 +297,8 @@ namespace Google.ProtocolBuffers.ProtoGen
method.Name, GetClassName(method.InputType), GetClassName(method.OutputType)); method.Name, GetClassName(method.InputType), GetClassName(method.OutputType));
} }
writer.WriteLine( writer.WriteLine(
"default: throw new global::System.MissingMethodException(typeof(I{0}).FullName, methodName);", Descriptor.Name); "default: throw new global::System.MissingMethodException(typeof(I{0}).FullName, methodName);",
Descriptor.Name);
writer.Outdent(); writer.Outdent();
writer.WriteLine("}"); //end switch writer.WriteLine("}"); //end switch
writer.Outdent(); writer.Outdent();
......
...@@ -35,6 +35,7 @@ ...@@ -35,6 +35,7 @@
#endregion #endregion
using System.Collections.Generic; using System.Collections.Generic;
using Google.ProtocolBuffers.DescriptorProtos;
using Google.ProtocolBuffers.Descriptors; using Google.ProtocolBuffers.Descriptors;
namespace Google.ProtocolBuffers.ProtoGen namespace Google.ProtocolBuffers.ProtoGen
...@@ -53,11 +54,11 @@ namespace Google.ProtocolBuffers.ProtoGen ...@@ -53,11 +54,11 @@ namespace Google.ProtocolBuffers.ProtoGen
this.descriptor = descriptor; this.descriptor = descriptor;
OptimizeSize = descriptor.File.Options.OptimizeFor == OptimizeSize = descriptor.File.Options.OptimizeFor ==
Google.ProtocolBuffers.DescriptorProtos.FileOptions.Types.OptimizeMode.CODE_SIZE; FileOptions.Types.OptimizeMode.CODE_SIZE;
OptimizeSpeed = descriptor.File.Options.OptimizeFor == OptimizeSpeed = descriptor.File.Options.OptimizeFor ==
Google.ProtocolBuffers.DescriptorProtos.FileOptions.Types.OptimizeMode.SPEED; FileOptions.Types.OptimizeMode.SPEED;
UseLiteRuntime = descriptor.File.Options.OptimizeFor == UseLiteRuntime = descriptor.File.Options.OptimizeFor ==
Google.ProtocolBuffers.DescriptorProtos.FileOptions.Types.OptimizeMode.LITE_RUNTIME; FileOptions.Types.OptimizeMode.LITE_RUNTIME;
//Lite runtime uses OptimizeSpeed code branches //Lite runtime uses OptimizeSpeed code branches
OptimizeSpeed |= UseLiteRuntime; OptimizeSpeed |= UseLiteRuntime;
RuntimeSuffix = UseLiteRuntime ? "Lite" : ""; RuntimeSuffix = UseLiteRuntime ? "Lite" : "";
......
...@@ -47,12 +47,12 @@ namespace Google.ProtocolBuffers.ProtoGen ...@@ -47,12 +47,12 @@ namespace Google.ProtocolBuffers.ProtoGen
private static readonly Dictionary<Type, Func<IDescriptor, ISourceGenerator>> GeneratorFactories = private static readonly Dictionary<Type, Func<IDescriptor, ISourceGenerator>> GeneratorFactories =
new Dictionary<Type, Func<IDescriptor, ISourceGenerator>> new Dictionary<Type, Func<IDescriptor, ISourceGenerator>>
{ {
{typeof(FileDescriptor),descriptor=>new UmbrellaClassGenerator((FileDescriptor)descriptor)}, {typeof (FileDescriptor), descriptor => new UmbrellaClassGenerator((FileDescriptor) descriptor)},
{typeof(EnumDescriptor),descriptor=>new EnumGenerator((EnumDescriptor)descriptor)}, {typeof (EnumDescriptor), descriptor => new EnumGenerator((EnumDescriptor) descriptor)},
{typeof(ServiceDescriptor),descriptor=>new ServiceGenerator((ServiceDescriptor)descriptor)}, {typeof (ServiceDescriptor), descriptor => new ServiceGenerator((ServiceDescriptor) descriptor)},
{typeof(MessageDescriptor),descriptor=>new MessageGenerator((MessageDescriptor)descriptor)}, {typeof (MessageDescriptor), descriptor => new MessageGenerator((MessageDescriptor) descriptor)},
// For other fields, we have IFieldSourceGenerators. // For other fields, we have IFieldSourceGenerators.
{typeof(FieldDescriptor),descriptor=>new ExtensionGenerator((FieldDescriptor)descriptor)} {typeof (FieldDescriptor), descriptor => new ExtensionGenerator((FieldDescriptor) descriptor)}
}; };
public static IFieldSourceGenerator CreateFieldGenerator(FieldDescriptor field, int fieldOrdinal) public static IFieldSourceGenerator CreateFieldGenerator(FieldDescriptor field, int fieldOrdinal)
...@@ -65,11 +65,11 @@ namespace Google.ProtocolBuffers.ProtoGen ...@@ -65,11 +65,11 @@ namespace Google.ProtocolBuffers.ProtoGen
: new MessageFieldGenerator(field, fieldOrdinal); : new MessageFieldGenerator(field, fieldOrdinal);
case MappedType.Enum: case MappedType.Enum:
return field.IsRepeated return field.IsRepeated
? (IFieldSourceGenerator)new RepeatedEnumFieldGenerator(field, fieldOrdinal) ? (IFieldSourceGenerator) new RepeatedEnumFieldGenerator(field, fieldOrdinal)
: new EnumFieldGenerator(field, fieldOrdinal); : new EnumFieldGenerator(field, fieldOrdinal);
default: default:
return field.IsRepeated return field.IsRepeated
? (IFieldSourceGenerator)new RepeatedPrimitiveFieldGenerator(field, fieldOrdinal) ? (IFieldSourceGenerator) new RepeatedPrimitiveFieldGenerator(field, fieldOrdinal)
: new PrimitiveFieldGenerator(field, fieldOrdinal); : new PrimitiveFieldGenerator(field, fieldOrdinal);
} }
} }
......
...@@ -163,7 +163,8 @@ namespace Google.ProtocolBuffers.ProtoGen ...@@ -163,7 +163,8 @@ namespace Google.ProtocolBuffers.ProtoGen
} }
writer.WriteLine("[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]"); writer.WriteLine("[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]");
writer.WriteLine("[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]"); writer.WriteLine("[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]");
writer.WriteLine("[global::System.CodeDom.Compiler.GeneratedCodeAttribute(\"{0}\", \"{1}\")]", GetType().Assembly.GetName().Name, GetType().Assembly.GetName().Version); writer.WriteLine("[global::System.CodeDom.Compiler.GeneratedCodeAttribute(\"{0}\", \"{1}\")]",
GetType().Assembly.GetName().Name, GetType().Assembly.GetName().Version);
writer.WriteLine("{0} static partial class {1} {{", ClassAccessLevel, writer.WriteLine("{0} static partial class {1} {{", ClassAccessLevel,
Descriptor.CSharpOptions.UmbrellaClassname); Descriptor.CSharpOptions.UmbrellaClassname);
writer.WriteLine(); writer.WriteLine();
......
...@@ -37,7 +37,6 @@ ...@@ -37,7 +37,6 @@
using System; using System;
using System.Collections; using System.Collections;
using System.Collections.Generic; using System.Collections.Generic;
using System.IO;
using Google.ProtocolBuffers.Descriptors; using Google.ProtocolBuffers.Descriptors;
namespace Google.ProtocolBuffers namespace Google.ProtocolBuffers
......
...@@ -35,8 +35,6 @@ ...@@ -35,8 +35,6 @@
#endregion #endregion
using System; using System;
using System.Collections;
using System.Collections.Generic;
using System.IO; using System.IO;
namespace Google.ProtocolBuffers namespace Google.ProtocolBuffers
......
...@@ -37,8 +37,10 @@ ...@@ -37,8 +37,10 @@
using System.Collections; using System.Collections;
using System.Collections.Generic; using System.Collections.Generic;
using System.IO; using System.IO;
using System.Text;
using Google.ProtocolBuffers.Collections; using Google.ProtocolBuffers.Collections;
using Google.ProtocolBuffers.Descriptors; using Google.ProtocolBuffers.Descriptors;
using Google.ProtocolBuffers.Serialization;
namespace Google.ProtocolBuffers namespace Google.ProtocolBuffers
{ {
...@@ -123,22 +125,22 @@ namespace Google.ProtocolBuffers ...@@ -123,22 +125,22 @@ namespace Google.ProtocolBuffers
public string ToJson() public string ToJson()
{ {
Serialization.JsonFormatWriter w = Serialization.JsonFormatWriter.CreateInstance(); JsonFormatWriter w = JsonFormatWriter.CreateInstance();
w.WriteMessage(this); w.WriteMessage(this);
return w.ToString(); return w.ToString();
} }
public string ToXml() public string ToXml()
{ {
StringWriter w = new StringWriter(new System.Text.StringBuilder(4096)); StringWriter w = new StringWriter(new StringBuilder(4096));
Serialization.XmlFormatWriter.CreateInstance(w).WriteMessage(this); XmlFormatWriter.CreateInstance(w).WriteMessage(this);
return w.ToString(); return w.ToString();
} }
public string ToXml(string rootElementName) public string ToXml(string rootElementName)
{ {
StringWriter w = new StringWriter(new System.Text.StringBuilder(4096)); StringWriter w = new StringWriter(new StringBuilder(4096));
Serialization.XmlFormatWriter.CreateInstance(w).WriteMessage(rootElementName, this); XmlFormatWriter.CreateInstance(w).WriteMessage(rootElementName, this);
return w.ToString(); return w.ToString();
} }
...@@ -170,28 +172,13 @@ namespace Google.ProtocolBuffers ...@@ -170,28 +172,13 @@ namespace Google.ProtocolBuffers
// IEnumerable is the best we can do. (C# generics aren't covariant yet.) // IEnumerable is the best we can do. (C# generics aren't covariant yet.)
IEnumerable valueList = (IEnumerable) entry.Value; IEnumerable valueList = (IEnumerable) entry.Value;
if (field.IsPacked) if (field.IsPacked)
{
output.WritePackedArray(field.FieldType, field.FieldNumber, field.Name, valueList); output.WritePackedArray(field.FieldType, field.FieldNumber, field.Name, valueList);
//{ }
// output.WriteTag(field.FieldNumber, WireFormat.WireType.LengthDelimited);
// int dataSize = 0;
// foreach (object element in valueList)
// {
// dataSize += CodedOutputStream.ComputeFieldSizeNoTag(field.FieldType, element);
// }
// output.WriteRawVarint32((uint) dataSize);
// foreach (object element in valueList)
// {
// output.WriteFieldNoTag(field.FieldType, element);
// }
//}
else else
{
output.WriteArray(field.FieldType, field.FieldNumber, field.Name, valueList); output.WriteArray(field.FieldType, field.FieldNumber, field.Name, valueList);
//{ }
// foreach (object element in valueList)
// {
// output.WriteField(field.FieldType, field.FieldNumber, field.Name, element);
// }
//}
} }
else else
{ {
......
...@@ -34,8 +34,6 @@ ...@@ -34,8 +34,6 @@
#endregion #endregion
using System.Collections;
using System.Collections.Generic;
using System.IO; using System.IO;
namespace Google.ProtocolBuffers namespace Google.ProtocolBuffers
......
...@@ -34,27 +34,35 @@ ...@@ -34,27 +34,35 @@
#endregion #endregion
using System;
namespace Google.ProtocolBuffers namespace Google.ProtocolBuffers
{ {
/// <summary> /// <summary>
/// Provides a utility routine to copy small arrays much more quickly than Buffer.BlockCopy /// Provides a utility routine to copy small arrays much more quickly than Buffer.BlockCopy
/// </summary> /// </summary>
static class ByteArray internal static class ByteArray
{ {
/// <summary> /// <summary>
/// The threshold above which you should use Buffer.BlockCopy rather than ByteArray.Copy /// The threshold above which you should use Buffer.BlockCopy rather than ByteArray.Copy
/// </summary> /// </summary>
const int CopyThreshold = 12; private const int CopyThreshold = 12;
/// <summary> /// <summary>
/// Determines which copy routine to use based on the number of bytes to be copied. /// Determines which copy routine to use based on the number of bytes to be copied.
/// </summary> /// </summary>
public static void Copy(byte[] src, int srcOffset, byte[] dst, int dstOffset, int count) public static void Copy(byte[] src, int srcOffset, byte[] dst, int dstOffset, int count)
{ {
if (count > CopyThreshold) if (count > CopyThreshold)
global::System.Buffer.BlockCopy(src, srcOffset, dst, dstOffset, count); {
Buffer.BlockCopy(src, srcOffset, dst, dstOffset, count);
}
else else
{
ByteCopy(src, srcOffset, dst, dstOffset, count); ByteCopy(src, srcOffset, dst, dstOffset, count);
} }
}
/// <summary> /// <summary>
/// Copy the bytes provided with a for loop, faster when there are only a few bytes to copy /// Copy the bytes provided with a for loop, faster when there are only a few bytes to copy
/// </summary> /// </summary>
...@@ -62,8 +70,11 @@ namespace Google.ProtocolBuffers ...@@ -62,8 +70,11 @@ namespace Google.ProtocolBuffers
{ {
int stop = srcOffset + count; int stop = srcOffset + count;
for (int i = srcOffset; i < stop; i++) for (int i = srcOffset; i < stop; i++)
{
dst[dstOffset++] = src[i]; dst[dstOffset++] = src[i];
} }
}
/// <summary> /// <summary>
/// Reverses the order of bytes in the array /// Reverses the order of bytes in the array
/// </summary> /// </summary>
......
...@@ -37,6 +37,7 @@ ...@@ -37,6 +37,7 @@
using System; using System;
using System.Collections; using System.Collections;
using System.Collections.Generic; using System.Collections.Generic;
using System.IO;
using System.Text; using System.Text;
namespace Google.ProtocolBuffers namespace Google.ProtocolBuffers
...@@ -91,7 +92,7 @@ namespace Google.ProtocolBuffers ...@@ -91,7 +92,7 @@ namespace Google.ProtocolBuffers
public byte[] ToByteArray() public byte[] ToByteArray()
{ {
return (byte[])bytes.Clone(); return (byte[]) bytes.Clone();
} }
public string ToBase64() public string ToBase64()
...@@ -104,7 +105,7 @@ namespace Google.ProtocolBuffers ...@@ -104,7 +105,7 @@ namespace Google.ProtocolBuffers
/// </summary> /// </summary>
public static ByteString FromBase64(string bytes) public static ByteString FromBase64(string bytes)
{ {
return new ByteString(System.Convert.FromBase64String(bytes)); return new ByteString(Convert.FromBase64String(bytes));
} }
/// <summary> /// <summary>
...@@ -267,7 +268,7 @@ namespace Google.ProtocolBuffers ...@@ -267,7 +268,7 @@ namespace Google.ProtocolBuffers
/// <summary> /// <summary>
/// Writes the entire byte array to the provided stream /// Writes the entire byte array to the provided stream
/// </summary> /// </summary>
public void WriteTo(System.IO.Stream outputStream) public void WriteTo(Stream outputStream)
{ {
outputStream.Write(bytes, 0, bytes.Length); outputStream.Write(bytes, 0, bytes.Length);
} }
......
This diff is collapsed.
...@@ -36,7 +36,6 @@ ...@@ -36,7 +36,6 @@
using System; using System;
using System.Globalization; using System.Globalization;
using System.IO;
using System.Text; using System.Text;
using Google.ProtocolBuffers.Descriptors; using Google.ProtocolBuffers.Descriptors;
...@@ -477,10 +476,22 @@ namespace Google.ProtocolBuffers ...@@ -477,10 +476,22 @@ namespace Google.ProtocolBuffers
[CLSCompliant(false)] [CLSCompliant(false)]
public static int ComputeRawVarint32Size(uint value) public static int ComputeRawVarint32Size(uint value)
{ {
if ((value & (0xffffffff << 7)) == 0) return 1; if ((value & (0xffffffff << 7)) == 0)
if ((value & (0xffffffff << 14)) == 0) return 2; {
if ((value & (0xffffffff << 21)) == 0) return 3; return 1;
if ((value & (0xffffffff << 28)) == 0) return 4; }
if ((value & (0xffffffff << 14)) == 0)
{
return 2;
}
if ((value & (0xffffffff << 21)) == 0)
{
return 3;
}
if ((value & (0xffffffff << 28)) == 0)
{
return 4;
}
return 5; return 5;
} }
...@@ -490,15 +501,42 @@ namespace Google.ProtocolBuffers ...@@ -490,15 +501,42 @@ namespace Google.ProtocolBuffers
[CLSCompliant(false)] [CLSCompliant(false)]
public static int ComputeRawVarint64Size(ulong value) public static int ComputeRawVarint64Size(ulong value)
{ {
if ((value & (0xffffffffffffffffL << 7)) == 0) return 1; if ((value & (0xffffffffffffffffL << 7)) == 0)
if ((value & (0xffffffffffffffffL << 14)) == 0) return 2; {
if ((value & (0xffffffffffffffffL << 21)) == 0) return 3; return 1;
if ((value & (0xffffffffffffffffL << 28)) == 0) return 4; }
if ((value & (0xffffffffffffffffL << 35)) == 0) return 5; if ((value & (0xffffffffffffffffL << 14)) == 0)
if ((value & (0xffffffffffffffffL << 42)) == 0) return 6; {
if ((value & (0xffffffffffffffffL << 49)) == 0) return 7; return 2;
if ((value & (0xffffffffffffffffL << 56)) == 0) return 8; }
if ((value & (0xffffffffffffffffL << 63)) == 0) return 9; if ((value & (0xffffffffffffffffL << 21)) == 0)
{
return 3;
}
if ((value & (0xffffffffffffffffL << 28)) == 0)
{
return 4;
}
if ((value & (0xffffffffffffffffL << 35)) == 0)
{
return 5;
}
if ((value & (0xffffffffffffffffL << 42)) == 0)
{
return 6;
}
if ((value & (0xffffffffffffffffL << 49)) == 0)
{
return 7;
}
if ((value & (0xffffffffffffffffL << 56)) == 0)
{
return 8;
}
if ((value & (0xffffffffffffffffL << 63)) == 0)
{
return 9;
}
return 10; return 10;
} }
...@@ -545,10 +583,14 @@ namespace Google.ProtocolBuffers ...@@ -545,10 +583,14 @@ namespace Google.ProtocolBuffers
case FieldType.SInt64: case FieldType.SInt64:
return ComputeSInt64Size(fieldNumber, (long) value); return ComputeSInt64Size(fieldNumber, (long) value);
case FieldType.Enum: case FieldType.Enum:
if (value is System.Enum) if (value is Enum)
return ComputeEnumSize(fieldNumber, ((IConvertible)value).ToInt32(CultureInfo.InvariantCulture)); {
return ComputeEnumSize(fieldNumber, ((IConvertible) value).ToInt32(CultureInfo.InvariantCulture));
}
else else
{
return ComputeEnumSize(fieldNumber, ((IEnumLite) value).Number); return ComputeEnumSize(fieldNumber, ((IEnumLite) value).Number);
}
default: default:
throw new ArgumentOutOfRangeException("Invalid field type " + fieldType); throw new ArgumentOutOfRangeException("Invalid field type " + fieldType);
} }
...@@ -597,10 +639,14 @@ namespace Google.ProtocolBuffers ...@@ -597,10 +639,14 @@ namespace Google.ProtocolBuffers
case FieldType.SInt64: case FieldType.SInt64:
return ComputeSInt64SizeNoTag((long) value); return ComputeSInt64SizeNoTag((long) value);
case FieldType.Enum: case FieldType.Enum:
if (value is System.Enum) if (value is Enum)
return ComputeEnumSizeNoTag(((IConvertible)value).ToInt32(CultureInfo.InvariantCulture)); {
return ComputeEnumSizeNoTag(((IConvertible) value).ToInt32(CultureInfo.InvariantCulture));
}
else else
{
return ComputeEnumSizeNoTag(((IEnumLite) value).Number); return ComputeEnumSizeNoTag(((IEnumLite) value).Number);
}
default: default:
throw new ArgumentOutOfRangeException("Invalid field type " + fieldType); throw new ArgumentOutOfRangeException("Invalid field type " + fieldType);
} }
......
This diff is collapsed.
...@@ -30,8 +30,8 @@ ...@@ -30,8 +30,8 @@
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System; using System;
using System.Collections.Generic;
using System.Collections; using System.Collections;
using System.Collections.Generic;
namespace Google.ProtocolBuffers.Collections namespace Google.ProtocolBuffers.Collections
{ {
...@@ -76,7 +76,14 @@ namespace Google.ProtocolBuffers.Collections ...@@ -76,7 +76,14 @@ namespace Google.ProtocolBuffers.Collections
public T this[int index] public T this[int index]
{ {
get { if (items == null) throw new ArgumentOutOfRangeException(); return items[index]; } get
{
if (items == null)
{
throw new ArgumentOutOfRangeException();
}
return items[index];
}
set set
{ {
ValidateModification(); ValidateModification();
...@@ -104,8 +111,10 @@ namespace Google.ProtocolBuffers.Collections ...@@ -104,8 +111,10 @@ namespace Google.ProtocolBuffers.Collections
public void CopyTo(T[] array, int arrayIndex) public void CopyTo(T[] array, int arrayIndex)
{ {
if (items != null) if (items != null)
{
items.CopyTo(array, arrayIndex); items.CopyTo(array, arrayIndex);
} }
}
public int Count public int Count
{ {
...@@ -140,7 +149,9 @@ namespace Google.ProtocolBuffers.Collections ...@@ -140,7 +149,9 @@ namespace Google.ProtocolBuffers.Collections
throw new NotSupportedException("List is read-only"); throw new NotSupportedException("List is read-only");
} }
if (items == null) if (items == null)
{
items = new List<T>(); items = new List<T>();
}
items.AddRange(collection); items.AddRange(collection);
} }
...@@ -151,14 +162,18 @@ namespace Google.ProtocolBuffers.Collections ...@@ -151,14 +162,18 @@ namespace Google.ProtocolBuffers.Collections
throw new NotSupportedException("List is read-only"); throw new NotSupportedException("List is read-only");
} }
if (items == null) if (items == null)
{
items = new List<T>(); items = new List<T>();
} }
}
IEnumerable<TItemType> ICastArray.CastArray<TItemType>() IEnumerable<TItemType> ICastArray.CastArray<TItemType>()
{ {
if (items == null) if (items == null)
{
return new TItemType[0]; return new TItemType[0];
return (TItemType[])(object)items.ToArray(); }
return (TItemType[]) (object) items.ToArray();
} }
} }
} }
\ No newline at end of file
...@@ -29,8 +29,8 @@ ...@@ -29,8 +29,8 @@
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System.Collections.Generic;
using System; using System;
using System.Collections.Generic;
using System.Text; using System.Text;
using System.Text.RegularExpressions; using System.Text.RegularExpressions;
......
...@@ -98,6 +98,7 @@ namespace Google.ProtocolBuffers.Descriptors ...@@ -98,6 +98,7 @@ namespace Google.ProtocolBuffers.Descriptors
{ {
return FindValueByNumber(number); return FindValueByNumber(number);
} }
IEnumLite IEnumLiteMap.FindValueByName(string name) IEnumLite IEnumLiteMap.FindValueByName(string name)
{ {
return FindValueByName(name); return FindValueByName(name);
......
...@@ -31,6 +31,7 @@ ...@@ -31,6 +31,7 @@
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Reflection;
using Google.ProtocolBuffers.Collections; using Google.ProtocolBuffers.Collections;
namespace Google.ProtocolBuffers.Descriptors namespace Google.ProtocolBuffers.Descriptors
...@@ -62,10 +63,7 @@ namespace Google.ProtocolBuffers.Descriptors ...@@ -62,10 +63,7 @@ namespace Google.ProtocolBuffers.Descriptors
private static IDictionary<FieldType, FieldMappingAttribute> MapFieldTypes() private static IDictionary<FieldType, FieldMappingAttribute> MapFieldTypes()
{ {
var map = new Dictionary<FieldType, FieldMappingAttribute>(); var map = new Dictionary<FieldType, FieldMappingAttribute>();
foreach ( foreach (FieldInfo field in typeof (FieldType).GetFields(BindingFlags.Static | BindingFlags.Public))
System.Reflection.FieldInfo field in
typeof (FieldType).GetFields(System.Reflection.BindingFlags.Static |
System.Reflection.BindingFlags.Public))
{ {
FieldType fieldType = (FieldType) field.GetValue(null); FieldType fieldType = (FieldType) field.GetValue(null);
FieldMappingAttribute mapping = FieldMappingAttribute mapping =
......
...@@ -264,7 +264,10 @@ namespace Google.ProtocolBuffers ...@@ -264,7 +264,10 @@ namespace Google.ProtocolBuffers
get get
{ {
int size = memoizedSize; int size = memoizedSize;
if (size != -1) return size; if (size != -1)
{
return size;
}
size = fields.SerializedSize; size = fields.SerializedSize;
if (type.Options.MessageSetWireFormat) if (type.Options.MessageSetWireFormat)
......
...@@ -36,9 +36,6 @@ ...@@ -36,9 +36,6 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Globalization;
using System.Reflection;
using System.Text;
namespace Google.ProtocolBuffers namespace Google.ProtocolBuffers
{ {
...@@ -110,8 +107,10 @@ namespace Google.ProtocolBuffers ...@@ -110,8 +107,10 @@ namespace Google.ProtocolBuffers
items.Add(Convert.ToInt32(evalue), new EnumValue(evalue)); items.Add(Convert.ToInt32(evalue), new EnumValue(evalue));
} }
#else #else
foreach (TEnum evalue in Enum.GetValues(typeof(TEnum))) foreach (TEnum evalue in Enum.GetValues(typeof (TEnum)))
{
items.Add(Convert.ToInt32(evalue), new EnumValue(evalue)); items.Add(Convert.ToInt32(evalue), new EnumValue(evalue));
}
#endif #endif
} }
...@@ -129,8 +128,10 @@ namespace Google.ProtocolBuffers ...@@ -129,8 +128,10 @@ namespace Google.ProtocolBuffers
public IEnumLite FindValueByName(string name) public IEnumLite FindValueByName(string name)
{ {
IEnumLite val; IEnumLite val;
if(Enum.IsDefined(typeof(TEnum), name)) if (Enum.IsDefined(typeof (TEnum), name))
return items.TryGetValue((int)Enum.Parse(typeof(TEnum), name, false), out val) ? val : null; {
return items.TryGetValue((int) Enum.Parse(typeof (TEnum), name, false), out val) ? val : null;
}
return null; return null;
} }
......
...@@ -142,8 +142,10 @@ namespace Google.ProtocolBuffers ...@@ -142,8 +142,10 @@ namespace Google.ProtocolBuffers
int fieldNumber = WireFormat.GetTagFieldNumber(tag); int fieldNumber = WireFormat.GetTagFieldNumber(tag);
IGeneratedExtensionLite extension = extensionRegistry[DefaultInstanceForType, fieldNumber]; IGeneratedExtensionLite extension = extensionRegistry[DefaultInstanceForType, fieldNumber];
if (extension == null)//unknown field if (extension == null) //unknown field
{
return input.SkipField(); return input.SkipField();
}
IFieldDescriptorLite field = extension.Descriptor; IFieldDescriptorLite field = extension.Descriptor;
...@@ -164,15 +166,20 @@ namespace Google.ProtocolBuffers ...@@ -164,15 +166,20 @@ namespace Google.ProtocolBuffers
//Allowed as of 2.3, this is unpacked data for a packed array //Allowed as of 2.3, this is unpacked data for a packed array
} }
else if (field.IsRepeated && wireType == WireFormat.WireType.LengthDelimited && else if (field.IsRepeated && wireType == WireFormat.WireType.LengthDelimited &&
(expectedType == WireFormat.WireType.Varint || expectedType == WireFormat.WireType.Fixed32 || expectedType == WireFormat.WireType.Fixed64)) (expectedType == WireFormat.WireType.Varint || expectedType == WireFormat.WireType.Fixed32 ||
expectedType == WireFormat.WireType.Fixed64))
{ {
//Allowed as of 2.3, this is packed data for an unpacked array //Allowed as of 2.3, this is packed data for an unpacked array
} }
else else
{
return input.SkipField(); return input.SkipField();
} }
}
if (!field.IsRepeated && wireType != WireFormat.GetWireType(field.FieldType)) //invalid wire type if (!field.IsRepeated && wireType != WireFormat.GetWireType(field.FieldType)) //invalid wire type
{
return input.SkipField(); return input.SkipField();
}
switch (field.FieldType) switch (field.FieldType)
{ {
...@@ -185,9 +192,13 @@ namespace Google.ProtocolBuffers ...@@ -185,9 +192,13 @@ namespace Google.ProtocolBuffers
IBuilderLite subBuilder = (message ?? extension.MessageDefaultInstance).WeakToBuilder(); IBuilderLite subBuilder = (message ?? extension.MessageDefaultInstance).WeakToBuilder();
if (field.FieldType == FieldType.Group) if (field.FieldType == FieldType.Group)
{
input.ReadGroup(field.FieldNumber, subBuilder, extensionRegistry); input.ReadGroup(field.FieldNumber, subBuilder, extensionRegistry);
}
else else
{
input.ReadMessage(subBuilder, extensionRegistry); input.ReadMessage(subBuilder, extensionRegistry);
}
extensions[field] = subBuilder.WeakBuild(); extensions[field] = subBuilder.WeakBuild();
} }
...@@ -195,12 +206,20 @@ namespace Google.ProtocolBuffers ...@@ -195,12 +206,20 @@ namespace Google.ProtocolBuffers
{ {
List<IMessageLite> list = new List<IMessageLite>(); List<IMessageLite> list = new List<IMessageLite>();
if (field.FieldType == FieldType.Group) if (field.FieldType == FieldType.Group)
input.ReadGroupArray(tag, fieldName, list, extension.MessageDefaultInstance, extensionRegistry); {
input.ReadGroupArray(tag, fieldName, list, extension.MessageDefaultInstance,
extensionRegistry);
}
else else
input.ReadMessageArray(tag, fieldName, list, extension.MessageDefaultInstance, extensionRegistry); {
input.ReadMessageArray(tag, fieldName, list, extension.MessageDefaultInstance,
extensionRegistry);
}
foreach (IMessageLite m in list) foreach (IMessageLite m in list)
{
extensions.AddRepeatedField(field, m); extensions.AddRepeatedField(field, m);
}
return true; return true;
} }
break; break;
...@@ -212,8 +231,10 @@ namespace Google.ProtocolBuffers ...@@ -212,8 +231,10 @@ namespace Google.ProtocolBuffers
object unknown; object unknown;
IEnumLite value = null; IEnumLite value = null;
if (input.ReadEnum(ref value, out unknown, field.EnumType)) if (input.ReadEnum(ref value, out unknown, field.EnumType))
{
extensions[field] = value; extensions[field] = value;
} }
}
else else
{ {
ICollection<object> unknown; ICollection<object> unknown;
...@@ -221,8 +242,10 @@ namespace Google.ProtocolBuffers ...@@ -221,8 +242,10 @@ namespace Google.ProtocolBuffers
input.ReadEnumArray(tag, fieldName, list, out unknown, field.EnumType); input.ReadEnumArray(tag, fieldName, list, out unknown, field.EnumType);
foreach (IEnumLite en in list) foreach (IEnumLite en in list)
{
extensions.AddRepeatedField(field, en); extensions.AddRepeatedField(field, en);
} }
}
break; break;
} }
default: default:
...@@ -231,15 +254,19 @@ namespace Google.ProtocolBuffers ...@@ -231,15 +254,19 @@ namespace Google.ProtocolBuffers
{ {
object value = null; object value = null;
if (input.ReadPrimitiveField(field.FieldType, ref value)) if (input.ReadPrimitiveField(field.FieldType, ref value))
{
extensions[field] = value; extensions[field] = value;
} }
}
else else
{ {
List<object> list = new List<object>(); List<object> list = new List<object>();
input.ReadPrimitiveArray(field.FieldType, tag, fieldName, list); input.ReadPrimitiveArray(field.FieldType, tag, fieldName, list);
foreach (object oval in list) foreach (object oval in list)
{
extensions.AddRepeatedField(field, oval); extensions.AddRepeatedField(field, oval);
} }
}
break; break;
} }
} }
......
...@@ -37,6 +37,7 @@ ...@@ -37,6 +37,7 @@
using System; using System;
using System.Collections; using System.Collections;
using System.Collections.Generic; using System.Collections.Generic;
using System.IO;
using Google.ProtocolBuffers.Collections; using Google.ProtocolBuffers.Collections;
namespace Google.ProtocolBuffers namespace Google.ProtocolBuffers
...@@ -74,7 +75,7 @@ namespace Google.ProtocolBuffers ...@@ -74,7 +75,7 @@ namespace Google.ProtocolBuffers
/// <summary> /// <summary>
/// writes the extensions to the text stream /// writes the extensions to the text stream
/// </summary> /// </summary>
public override void PrintTo(System.IO.TextWriter writer) public override void PrintTo(TextWriter writer)
{ {
foreach (KeyValuePair<IFieldDescriptorLite, object> entry in extensions.AllFields) foreach (KeyValuePair<IFieldDescriptorLite, object> entry in extensions.AllFields)
{ {
...@@ -82,8 +83,10 @@ namespace Google.ProtocolBuffers ...@@ -82,8 +83,10 @@ namespace Google.ProtocolBuffers
if (entry.Key.IsRepeated) if (entry.Key.IsRepeated)
{ {
foreach (object o in ((IEnumerable) entry.Value)) foreach (object o in ((IEnumerable) entry.Value))
{
PrintField(fn, true, o, writer); PrintField(fn, true, o, writer);
} }
}
else else
{ {
PrintField(fn, true, entry.Value, writer); PrintField(fn, true, entry.Value, writer);
......
...@@ -34,9 +34,9 @@ ...@@ -34,9 +34,9 @@
#endregion #endregion
using System;
using System.Collections.Generic; using System.Collections.Generic;
using Google.ProtocolBuffers.Descriptors; using Google.ProtocolBuffers.Descriptors;
using System;
namespace Google.ProtocolBuffers namespace Google.ProtocolBuffers
{ {
...@@ -107,8 +107,10 @@ namespace Google.ProtocolBuffers ...@@ -107,8 +107,10 @@ namespace Google.ProtocolBuffers
foreach (IGeneratedExtensionLite ext in extensionsByNumber.Values) foreach (IGeneratedExtensionLite ext in extensionsByNumber.Values)
{ {
if (StringComparer.Ordinal.Equals(ext.Descriptor.FullName, fullName)) if (StringComparer.Ordinal.Equals(ext.Descriptor.FullName, fullName))
{
return ext as ExtensionInfo; return ext as ExtensionInfo;
} }
}
return null; return null;
} }
} }
...@@ -204,8 +206,10 @@ namespace Google.ProtocolBuffers ...@@ -204,8 +206,10 @@ namespace Google.ProtocolBuffers
// up by type name. // up by type name.
Dictionary<string, IGeneratedExtensionLite> map; Dictionary<string, IGeneratedExtensionLite> map;
if (extensionsByName.TryGetValue(liteExtension.ContainingType, out map)) if (extensionsByName.TryGetValue(liteExtension.ContainingType, out map))
{
map[field.MessageType.FullName] = extension; map[field.MessageType.FullName] = extension;
} }
} }
} }
}
} }
\ No newline at end of file
...@@ -34,9 +34,8 @@ ...@@ -34,9 +34,8 @@
#endregion #endregion
using System.Collections.Generic;
using System; using System;
using Google.ProtocolBuffers.Descriptors; using System.Collections.Generic;
namespace Google.ProtocolBuffers namespace Google.ProtocolBuffers
{ {
...@@ -93,8 +92,13 @@ namespace Google.ProtocolBuffers ...@@ -93,8 +92,13 @@ namespace Google.ProtocolBuffers
/// </remarks> /// </remarks>
public sealed partial class ExtensionRegistry public sealed partial class ExtensionRegistry
{ {
class ExtensionByNameMap : Dictionary<object, Dictionary<string, IGeneratedExtensionLite>> { } private class ExtensionByNameMap : Dictionary<object, Dictionary<string, IGeneratedExtensionLite>>
class ExtensionByIdMap : Dictionary<ExtensionIntPair, IGeneratedExtensionLite> { } {
}
private class ExtensionByIdMap : Dictionary<ExtensionIntPair, IGeneratedExtensionLite>
{
}
private static readonly ExtensionRegistry empty = new ExtensionRegistry( private static readonly ExtensionRegistry empty = new ExtensionRegistry(
new ExtensionByNameMap(), new ExtensionByNameMap(),
...@@ -149,14 +153,18 @@ namespace Google.ProtocolBuffers ...@@ -149,14 +153,18 @@ namespace Google.ProtocolBuffers
} }
public IGeneratedExtensionLite FindByName(IMessageLite defaultInstanceOfType, string fieldName) public IGeneratedExtensionLite FindByName(IMessageLite defaultInstanceOfType, string fieldName)
{ return FindExtensionByName(defaultInstanceOfType, fieldName); } {
return FindExtensionByName(defaultInstanceOfType, fieldName);
}
IGeneratedExtensionLite FindExtensionByName(object forwhat, string fieldName) private IGeneratedExtensionLite FindExtensionByName(object forwhat, string fieldName)
{ {
IGeneratedExtensionLite extension = null; IGeneratedExtensionLite extension = null;
Dictionary<string, IGeneratedExtensionLite> map; Dictionary<string, IGeneratedExtensionLite> map;
if (extensionsByName.TryGetValue(forwhat, out map) && map.TryGetValue(fieldName, out extension)) if (extensionsByName.TryGetValue(forwhat, out map) && map.TryGetValue(fieldName, out extension))
{
return extension; return extension;
}
return null; return null;
} }
...@@ -173,7 +181,9 @@ namespace Google.ProtocolBuffers ...@@ -173,7 +181,9 @@ namespace Google.ProtocolBuffers
Dictionary<string, IGeneratedExtensionLite> map; Dictionary<string, IGeneratedExtensionLite> map;
if (!extensionsByName.TryGetValue(extension.ContainingType, out map)) if (!extensionsByName.TryGetValue(extension.ContainingType, out map))
{
extensionsByName.Add(extension.ContainingType, map = new Dictionary<string, IGeneratedExtensionLite>()); extensionsByName.Add(extension.ContainingType, map = new Dictionary<string, IGeneratedExtensionLite>());
}
map[extension.Descriptor.Name] = extension; map[extension.Descriptor.Name] = extension;
map[extension.Descriptor.FullName] = extension; map[extension.Descriptor.FullName] = extension;
} }
...@@ -195,7 +205,7 @@ namespace Google.ProtocolBuffers ...@@ -195,7 +205,7 @@ namespace Google.ProtocolBuffers
public override int GetHashCode() public override int GetHashCode()
{ {
return msgType.GetHashCode() * ((1 << 16) - 1) + number; return msgType.GetHashCode()*((1 << 16) - 1) + number;
} }
public override bool Equals(object obj) public override bool Equals(object obj)
...@@ -204,7 +214,7 @@ namespace Google.ProtocolBuffers ...@@ -204,7 +214,7 @@ namespace Google.ProtocolBuffers
{ {
return false; return false;
} }
return Equals((ExtensionIntPair)obj); return Equals((ExtensionIntPair) obj);
} }
public bool Equals(ExtensionIntPair other) public bool Equals(ExtensionIntPair other)
......
...@@ -62,7 +62,10 @@ namespace Google.ProtocolBuffers.FieldAccess ...@@ -62,7 +62,10 @@ namespace Google.ProtocolBuffers.FieldAccess
{ {
PropertyInfo messageProperty = typeof (TMessage).GetProperty(name); PropertyInfo messageProperty = typeof (TMessage).GetProperty(name);
PropertyInfo builderProperty = typeof (TBuilder).GetProperty(name); PropertyInfo builderProperty = typeof (TBuilder).GetProperty(name);
if (builderProperty == null) builderProperty = typeof (TBuilder).GetProperty(name); if (builderProperty == null)
{
builderProperty = typeof (TBuilder).GetProperty(name);
}
PropertyInfo hasProperty = typeof (TMessage).GetProperty("Has" + name); PropertyInfo hasProperty = typeof (TMessage).GetProperty("Has" + name);
MethodInfo clearMethod = typeof (TBuilder).GetMethod("Clear" + name, EmptyTypes); MethodInfo clearMethod = typeof (TBuilder).GetMethod("Clear" + name, EmptyTypes);
if (messageProperty == null || builderProperty == null || hasProperty == null || clearMethod == null) if (messageProperty == null || builderProperty == null || hasProperty == null || clearMethod == null)
......
...@@ -147,14 +147,16 @@ namespace Google.ProtocolBuffers ...@@ -147,14 +147,16 @@ namespace Google.ProtocolBuffers
/// <summary> /// <summary>
/// Force coercion to full descriptor dictionary. /// Force coercion to full descriptor dictionary.
/// </summary> /// </summary>
internal IDictionary<Descriptors.FieldDescriptor, object> AllFieldDescriptors internal IDictionary<FieldDescriptor, object> AllFieldDescriptors
{ {
get get
{ {
SortedList<Descriptors.FieldDescriptor, object> copy = SortedList<FieldDescriptor, object> copy =
new SortedList<Google.ProtocolBuffers.Descriptors.FieldDescriptor, object>(); new SortedList<FieldDescriptor, object>();
foreach (KeyValuePair<IFieldDescriptorLite, object> fd in fields) foreach (KeyValuePair<IFieldDescriptorLite, object> fd in fields)
copy.Add((Descriptors.FieldDescriptor) fd.Key, fd.Value); {
copy.Add((FieldDescriptor) fd.Key, fd.Value);
}
return Dictionaries.AsReadOnly(copy); return Dictionaries.AsReadOnly(copy);
} }
} }
...@@ -395,9 +397,11 @@ namespace Google.ProtocolBuffers ...@@ -395,9 +397,11 @@ namespace Google.ProtocolBuffers
/// </summary> /// </summary>
public void MergeFrom(IMessage other) public void MergeFrom(IMessage other)
{ {
foreach (KeyValuePair<Descriptors.FieldDescriptor, object> fd in other.AllFields) foreach (KeyValuePair<FieldDescriptor, object> fd in other.AllFields)
{
MergeField(fd.Key, fd.Value); MergeField(fd.Key, fd.Value);
} }
}
#endif #endif
/// <summary> /// <summary>
...@@ -470,7 +474,7 @@ namespace Google.ProtocolBuffers ...@@ -470,7 +474,7 @@ namespace Google.ProtocolBuffers
{ {
if (field.IsExtension && field.MessageSetWireFormat) if (field.IsExtension && field.MessageSetWireFormat)
{ {
output.WriteMessageSetExtension(field.FieldNumber, field.Name, (IMessageLite)value); output.WriteMessageSetExtension(field.FieldNumber, field.Name, (IMessageLite) value);
} }
else else
{ {
...@@ -478,30 +482,13 @@ namespace Google.ProtocolBuffers ...@@ -478,30 +482,13 @@ namespace Google.ProtocolBuffers
{ {
IEnumerable valueList = (IEnumerable) value; IEnumerable valueList = (IEnumerable) value;
if (field.IsPacked) if (field.IsPacked)
{
output.WritePackedArray(field.FieldType, field.FieldNumber, field.Name, valueList); output.WritePackedArray(field.FieldType, field.FieldNumber, field.Name, valueList);
//{ }
// output.WriteTag(field.FieldNumber, WireFormat.WireType.LengthDelimited);
// // Compute the total data size so the length can be written.
// int dataSize = 0;
// foreach (object element in valueList)
// {
// dataSize += CodedOutputStream.ComputeFieldSizeNoTag(field.FieldType, element);
// }
// output.WriteRawVarint32((uint) dataSize);
// // Write the data itself, without any tags.
// foreach (object element in valueList)
// {
// output.WriteFieldNoTag(field.FieldType, element);
// }
//}
else else
{
output.WriteArray(field.FieldType, field.FieldNumber, field.Name, valueList); output.WriteArray(field.FieldType, field.FieldNumber, field.Name, valueList);
//{ }
// foreach (object element in valueList)
// {
// output.WriteField(field.FieldType, field.FieldNumber, field.Name, element);
// }
//}
} }
else else
{ {
...@@ -629,8 +616,8 @@ namespace Google.ProtocolBuffers ...@@ -629,8 +616,8 @@ namespace Google.ProtocolBuffers
// field name and other useful info in the exception. // field name and other useful info in the exception.
string message = "Wrong object type used with protocol message reflection."; string message = "Wrong object type used with protocol message reflection.";
#if !LITE #if !LITE
Google.ProtocolBuffers.Descriptors.FieldDescriptor fieldinfo = FieldDescriptor fieldinfo =
field as Google.ProtocolBuffers.Descriptors.FieldDescriptor; field as FieldDescriptor;
if (fieldinfo != null) if (fieldinfo != null)
{ {
message += "Message type \"" + fieldinfo.ContainingType.FullName; message += "Message type \"" + fieldinfo.ContainingType.FullName;
......
...@@ -35,7 +35,6 @@ ...@@ -35,7 +35,6 @@
#endregion #endregion
using System; using System;
using System.Collections;
using System.Collections.Generic; using System.Collections.Generic;
namespace Google.ProtocolBuffers namespace Google.ProtocolBuffers
......
...@@ -34,10 +34,8 @@ ...@@ -34,10 +34,8 @@
#endregion #endregion
using System;
using System.Collections; using System.Collections;
using System.Collections.Generic; using System.Collections.Generic;
using Google.ProtocolBuffers.Collections;
using Google.ProtocolBuffers.Descriptors; using Google.ProtocolBuffers.Descriptors;
namespace Google.ProtocolBuffers namespace Google.ProtocolBuffers
...@@ -81,7 +79,9 @@ namespace Google.ProtocolBuffers ...@@ -81,7 +79,9 @@ namespace Google.ProtocolBuffers
string name = fullName; string name = fullName;
int offset = name.LastIndexOf('.'); int offset = name.LastIndexOf('.');
if (offset >= 0) if (offset >= 0)
{
name = name.Substring(offset); name = name.Substring(offset);
}
return name; return name;
} }
} }
......
...@@ -35,11 +35,14 @@ ...@@ -35,11 +35,14 @@
#endregion #endregion
using System; using System;
using System.Collections;
using System.Collections.Generic; using System.Collections.Generic;
using System.IO;
using System.Xml;
using Google.ProtocolBuffers.Collections; using Google.ProtocolBuffers.Collections;
using Google.ProtocolBuffers.Descriptors; using Google.ProtocolBuffers.Descriptors;
using Google.ProtocolBuffers.FieldAccess; using Google.ProtocolBuffers.FieldAccess;
using System.Collections; using Google.ProtocolBuffers.Serialization;
namespace Google.ProtocolBuffers namespace Google.ProtocolBuffers
{ {
...@@ -178,30 +181,37 @@ namespace Google.ProtocolBuffers ...@@ -178,30 +181,37 @@ namespace Google.ProtocolBuffers
public static TMessage ParseFromJson(string jsonText) public static TMessage ParseFromJson(string jsonText)
{ {
return Serialization.JsonFormatReader.CreateInstance(jsonText) return JsonFormatReader.CreateInstance(jsonText)
.Merge(new TBuilder()) .Merge(new TBuilder())
.Build(); .Build();
} }
public static TMessage ParseFromJson(System.IO.TextReader reader) public static TMessage ParseFromJson(TextReader reader)
{ return ParseFromJson(reader, ExtensionRegistry.Empty); } {
return ParseFromJson(reader, ExtensionRegistry.Empty);
}
public static TMessage ParseFromJson(System.IO.TextReader reader, ExtensionRegistry extensionRegistry) public static TMessage ParseFromJson(TextReader reader, ExtensionRegistry extensionRegistry)
{ {
return Serialization.JsonFormatReader.CreateInstance(reader) return JsonFormatReader.CreateInstance(reader)
.Merge(new TBuilder(), extensionRegistry) .Merge(new TBuilder(), extensionRegistry)
.Build(); .Build();
} }
public static TMessage ParseFromXml(System.Xml.XmlReader reader) public static TMessage ParseFromXml(XmlReader reader)
{ return ParseFromXml(Serialization.XmlFormatReader.DefaultRootElementName, reader, ExtensionRegistry.Empty); } {
return ParseFromXml(XmlFormatReader.DefaultRootElementName, reader, ExtensionRegistry.Empty);
}
public static TMessage ParseFromXml(string rootElementName, System.Xml.XmlReader reader) public static TMessage ParseFromXml(string rootElementName, XmlReader reader)
{ return ParseFromXml(rootElementName, reader, ExtensionRegistry.Empty); } {
return ParseFromXml(rootElementName, reader, ExtensionRegistry.Empty);
}
public static TMessage ParseFromXml(string rootElementName, System.Xml.XmlReader reader, ExtensionRegistry extensionRegistry) public static TMessage ParseFromXml(string rootElementName, XmlReader reader,
ExtensionRegistry extensionRegistry)
{ {
return Serialization.XmlFormatReader.CreateInstance(reader) return XmlFormatReader.CreateInstance(reader)
.Merge(rootElementName, new TBuilder(), extensionRegistry) .Merge(rootElementName, new TBuilder(), extensionRegistry)
.Build(); .Build();
} }
......
...@@ -36,9 +36,9 @@ ...@@ -36,9 +36,9 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Collections;
using System.Globalization; using System.Globalization;
using Google.ProtocolBuffers.Descriptors; using System.IO;
using System.Text;
namespace Google.ProtocolBuffers namespace Google.ProtocolBuffers
{ {
...@@ -55,7 +55,7 @@ namespace Google.ProtocolBuffers ...@@ -55,7 +55,7 @@ namespace Google.ProtocolBuffers
public override sealed string ToString() public override sealed string ToString()
{ {
using (System.IO.StringWriter wtr = new System.IO.StringWriter()) using (StringWriter wtr = new StringWriter())
{ {
PrintTo(wtr); PrintTo(wtr);
return wtr.ToString(); return wtr.ToString();
...@@ -65,18 +65,23 @@ namespace Google.ProtocolBuffers ...@@ -65,18 +65,23 @@ namespace Google.ProtocolBuffers
/// <summary> /// <summary>
/// PrintTo() helper methods for Lite Runtime /// PrintTo() helper methods for Lite Runtime
/// </summary> /// </summary>
protected static void PrintField<T>(string name, IList<T> value, System.IO.TextWriter writer) protected static void PrintField<T>(string name, IList<T> value, TextWriter writer)
{ {
foreach (T item in value) foreach (T item in value)
{
PrintField(name, true, (object) item, writer); PrintField(name, true, (object) item, writer);
} }
}
/// <summary> /// <summary>
/// PrintTo() helper methods for Lite Runtime /// PrintTo() helper methods for Lite Runtime
/// </summary> /// </summary>
protected static void PrintField(string name, bool hasValue, object value, System.IO.TextWriter writer) protected static void PrintField(string name, bool hasValue, object value, TextWriter writer)
{ {
if (!hasValue) return; if (!hasValue)
{
return;
}
if (value is IMessageLite) if (value is IMessageLite)
{ {
writer.WriteLine("{0} {{", name); writer.WriteLine("{0} {{", name);
...@@ -87,9 +92,13 @@ namespace Google.ProtocolBuffers ...@@ -87,9 +92,13 @@ namespace Google.ProtocolBuffers
{ {
writer.Write("{0}: \"", name); writer.Write("{0}: \"", name);
if (value is String) if (value is String)
EscapeBytes(System.Text.Encoding.UTF8.GetBytes((string) value), writer); {
EscapeBytes(Encoding.UTF8.GetBytes((string) value), writer);
}
else else
{
EscapeBytes(((ByteString) value), writer); EscapeBytes(((ByteString) value), writer);
}
writer.WriteLine("\""); writer.WriteLine("\"");
} }
else if (value is bool) else if (value is bool)
...@@ -116,7 +125,7 @@ namespace Google.ProtocolBuffers ...@@ -116,7 +125,7 @@ namespace Google.ProtocolBuffers
/// using 3-digit octal sequences. /// using 3-digit octal sequences.
/// The returned value is guaranteed to be entirely ASCII. /// The returned value is guaranteed to be entirely ASCII.
/// </summary> /// </summary>
private static void EscapeBytes(IEnumerable<byte> input, System.IO.TextWriter writer) private static void EscapeBytes(IEnumerable<byte> input, TextWriter writer)
{ {
foreach (byte b in input) foreach (byte b in input)
{ {
......
...@@ -35,9 +35,9 @@ ...@@ -35,9 +35,9 @@
#endregion #endregion
using System; using System;
using System.Collections;
using System.Collections.Generic; using System.Collections.Generic;
using Google.ProtocolBuffers.Descriptors; using Google.ProtocolBuffers.Descriptors;
using System.Collections;
namespace Google.ProtocolBuffers namespace Google.ProtocolBuffers
{ {
......
...@@ -34,8 +34,6 @@ ...@@ -34,8 +34,6 @@
#endregion #endregion
using System;
using System.Collections.Generic;
using System.IO; using System.IO;
namespace Google.ProtocolBuffers namespace Google.ProtocolBuffers
......
...@@ -187,7 +187,8 @@ namespace Google.ProtocolBuffers ...@@ -187,7 +187,8 @@ namespace Google.ProtocolBuffers
/// read a packed array. /// read a packed array.
/// </summary> /// </summary>
[CLSCompliant(false)] [CLSCompliant(false)]
void ReadEnumArray(uint fieldTag, string fieldName, ICollection<IEnumLite> list, out ICollection<object> unknown, IEnumLiteMap mapping); void ReadEnumArray(uint fieldTag, string fieldName, ICollection<IEnumLite> list, out ICollection<object> unknown,
IEnumLiteMap mapping);
/// <summary> /// <summary>
/// Reads an array of primitive values into the list, if the wire-type of fieldTag is length-prefixed, it will /// Reads an array of primitive values into the list, if the wire-type of fieldTag is length-prefixed, it will
...@@ -202,13 +203,15 @@ namespace Google.ProtocolBuffers ...@@ -202,13 +203,15 @@ namespace Google.ProtocolBuffers
/// the most derived type, it is only the type specifier for the collection. /// the most derived type, it is only the type specifier for the collection.
/// </summary> /// </summary>
[CLSCompliant(false)] [CLSCompliant(false)]
void ReadMessageArray<T>(uint fieldTag, string fieldName, ICollection<T> list, T messageType, ExtensionRegistry registry) where T : IMessageLite; void ReadMessageArray<T>(uint fieldTag, string fieldName, ICollection<T> list, T messageType,
ExtensionRegistry registry) where T : IMessageLite;
/// <summary> /// <summary>
/// Reads a set of messages using the <paramref name="messageType"/> as a template. /// Reads a set of messages using the <paramref name="messageType"/> as a template.
/// </summary> /// </summary>
[CLSCompliant(false)] [CLSCompliant(false)]
void ReadGroupArray<T>(uint fieldTag, string fieldName, ICollection<T> list, T messageType, ExtensionRegistry registry) where T : IMessageLite; void ReadGroupArray<T>(uint fieldTag, string fieldName, ICollection<T> list, T messageType,
ExtensionRegistry registry) where T : IMessageLite;
/// <summary> /// <summary>
/// Reads a field of any primitive type. Enums, groups and embedded /// Reads a field of any primitive type. Enums, groups and embedded
......
...@@ -35,6 +35,7 @@ ...@@ -35,6 +35,7 @@
#endregion #endregion
using System; using System;
using System.Collections;
using System.Collections.Generic; using System.Collections.Generic;
using Google.ProtocolBuffers.Descriptors; using Google.ProtocolBuffers.Descriptors;
...@@ -49,7 +50,9 @@ namespace Google.ProtocolBuffers ...@@ -49,7 +50,9 @@ namespace Google.ProtocolBuffers
[Obsolete] [Obsolete]
void WriteUnknownGroup(int fieldNumber, IMessageLite value); void WriteUnknownGroup(int fieldNumber, IMessageLite value);
void WriteUnknownBytes(int fieldNumber, ByteString value); void WriteUnknownBytes(int fieldNumber, ByteString value);
[CLSCompliant(false)] [CLSCompliant(false)]
void WriteUnknownField(int fieldNumber, WireFormat.WireType wireType, ulong value); void WriteUnknownField(int fieldNumber, WireFormat.WireType wireType, ulong value);
...@@ -115,6 +118,7 @@ namespace Google.ProtocolBuffers ...@@ -115,6 +118,7 @@ namespace Google.ProtocolBuffers
/// Writes a message field value, including tag, to the stream. /// Writes a message field value, including tag, to the stream.
/// </summary> /// </summary>
void WriteMessage(int fieldNumber, string fieldName, IMessageLite value); void WriteMessage(int fieldNumber, string fieldName, IMessageLite value);
/// <summary> /// <summary>
/// Writes a byte array field value, including tag, to the stream. /// Writes a byte array field value, including tag, to the stream.
/// </summary> /// </summary>
...@@ -130,24 +134,28 @@ namespace Google.ProtocolBuffers ...@@ -130,24 +134,28 @@ namespace Google.ProtocolBuffers
/// Writes an enum field value, including tag, to the stream. /// Writes an enum field value, including tag, to the stream.
/// </summary> /// </summary>
void WriteEnum(int fieldNumber, string fieldName, int value, object rawValue); void WriteEnum(int fieldNumber, string fieldName, int value, object rawValue);
/// <summary> /// <summary>
/// Writes a fixed 32-bit field value, including tag, to the stream. /// Writes a fixed 32-bit field value, including tag, to the stream.
/// </summary> /// </summary>
void WriteSFixed32(int fieldNumber, string fieldName, int value); void WriteSFixed32(int fieldNumber, string fieldName, int value);
/// <summary> /// <summary>
/// Writes a signed fixed 64-bit field value, including tag, to the stream. /// Writes a signed fixed 64-bit field value, including tag, to the stream.
/// </summary> /// </summary>
void WriteSFixed64(int fieldNumber, string fieldName, long value); void WriteSFixed64(int fieldNumber, string fieldName, long value);
/// <summary> /// <summary>
/// Writes a signed 32-bit field value, including tag, to the stream. /// Writes a signed 32-bit field value, including tag, to the stream.
/// </summary> /// </summary>
void WriteSInt32(int fieldNumber, string fieldName, int value); void WriteSInt32(int fieldNumber, string fieldName, int value);
/// <summary> /// <summary>
/// Writes a signed 64-bit field value, including tag, to the stream. /// Writes a signed 64-bit field value, including tag, to the stream.
/// </summary> /// </summary>
void WriteSInt64(int fieldNumber, string fieldName, long value); void WriteSInt64(int fieldNumber, string fieldName, long value);
void WriteArray(FieldType fieldType, int fieldNumber, string fieldName, System.Collections.IEnumerable list); void WriteArray(FieldType fieldType, int fieldNumber, string fieldName, IEnumerable list);
void WriteGroupArray<T>(int fieldNumber, string fieldName, IEnumerable<T> list) void WriteGroupArray<T>(int fieldNumber, string fieldName, IEnumerable<T> list)
where T : IMessageLite; where T : IMessageLite;
...@@ -189,7 +197,7 @@ namespace Google.ProtocolBuffers ...@@ -189,7 +197,7 @@ namespace Google.ProtocolBuffers
void WriteEnumArray<T>(int fieldNumber, string fieldName, IEnumerable<T> list) void WriteEnumArray<T>(int fieldNumber, string fieldName, IEnumerable<T> list)
where T : struct, IComparable, IFormattable, IConvertible; where T : struct, IComparable, IFormattable, IConvertible;
void WritePackedArray(FieldType fieldType, int fieldNumber, string fieldName, System.Collections.IEnumerable list); void WritePackedArray(FieldType fieldType, int fieldNumber, string fieldName, IEnumerable list);
void WritePackedBoolArray(int fieldNumber, string fieldName, int calculatedSize, IEnumerable<bool> list); void WritePackedBoolArray(int fieldNumber, string fieldName, int calculatedSize, IEnumerable<bool> list);
......
...@@ -34,8 +34,6 @@ ...@@ -34,8 +34,6 @@
#endregion #endregion
using System;
using System.Collections.Generic;
using System.IO; using System.IO;
namespace Google.ProtocolBuffers namespace Google.ProtocolBuffers
......
...@@ -34,8 +34,6 @@ ...@@ -34,8 +34,6 @@
#endregion #endregion
using System;
namespace Google.ProtocolBuffers namespace Google.ProtocolBuffers
{ {
/// <summary> /// <summary>
......
...@@ -35,8 +35,8 @@ ...@@ -35,8 +35,8 @@
#endregion #endregion
using System; using System;
using System.Collections.Generic;
using System.Collections; using System.Collections;
using System.Collections.Generic;
using System.IO; using System.IO;
using System.Reflection; using System.Reflection;
...@@ -223,9 +223,13 @@ namespace Google.ProtocolBuffers ...@@ -223,9 +223,13 @@ namespace Google.ProtocolBuffers
while (input.ReadTag(out tag, out name)) while (input.ReadTag(out tag, out name))
{ {
if ((tag == 0 && name == "item") || (tag == ExpectedTag)) if ((tag == 0 && name == "item") || (tag == ExpectedTag))
{
yield return messageReader(input, extensionRegistry); yield return messageReader(input, extensionRegistry);
}
else else
{
throw InvalidProtocolBufferException.InvalidMessageStreamTag(); throw InvalidProtocolBufferException.InvalidMessageStreamTag();
}
input.ResetSizeCounter(); input.ResetSizeCounter();
} }
......
...@@ -34,8 +34,8 @@ ...@@ -34,8 +34,8 @@
#endregion #endregion
using System.Text;
using System.Globalization; using System.Globalization;
using System.Text;
namespace Google.ProtocolBuffers namespace Google.ProtocolBuffers
{ {
......
...@@ -20,7 +20,7 @@ namespace Google.ProtocolBuffers.Serialization ...@@ -20,7 +20,7 @@ namespace Google.ProtocolBuffers.Serialization
protected override bool Read(ref string value) protected override bool Read(ref string value)
{ {
string text = null; string text = null;
if (ReadAsText(ref text, typeof(string))) if (ReadAsText(ref text, typeof (string)))
{ {
value = text; value = text;
return true; return true;
...@@ -34,7 +34,7 @@ namespace Google.ProtocolBuffers.Serialization ...@@ -34,7 +34,7 @@ namespace Google.ProtocolBuffers.Serialization
protected override bool Read(ref bool value) protected override bool Read(ref bool value)
{ {
string text = null; string text = null;
if (ReadAsText(ref text, typeof(bool))) if (ReadAsText(ref text, typeof (bool)))
{ {
value = XmlConvert.ToBoolean(text); value = XmlConvert.ToBoolean(text);
return true; return true;
...@@ -48,7 +48,7 @@ namespace Google.ProtocolBuffers.Serialization ...@@ -48,7 +48,7 @@ namespace Google.ProtocolBuffers.Serialization
protected override bool Read(ref int value) protected override bool Read(ref int value)
{ {
string text = null; string text = null;
if (ReadAsText(ref text, typeof(int))) if (ReadAsText(ref text, typeof (int)))
{ {
value = XmlConvert.ToInt32(text); value = XmlConvert.ToInt32(text);
return true; return true;
...@@ -63,7 +63,7 @@ namespace Google.ProtocolBuffers.Serialization ...@@ -63,7 +63,7 @@ namespace Google.ProtocolBuffers.Serialization
protected override bool Read(ref uint value) protected override bool Read(ref uint value)
{ {
string text = null; string text = null;
if (ReadAsText(ref text, typeof(uint))) if (ReadAsText(ref text, typeof (uint)))
{ {
value = XmlConvert.ToUInt32(text); value = XmlConvert.ToUInt32(text);
return true; return true;
...@@ -77,7 +77,7 @@ namespace Google.ProtocolBuffers.Serialization ...@@ -77,7 +77,7 @@ namespace Google.ProtocolBuffers.Serialization
protected override bool Read(ref long value) protected override bool Read(ref long value)
{ {
string text = null; string text = null;
if (ReadAsText(ref text, typeof(long))) if (ReadAsText(ref text, typeof (long)))
{ {
value = XmlConvert.ToInt64(text); value = XmlConvert.ToInt64(text);
return true; return true;
...@@ -92,7 +92,7 @@ namespace Google.ProtocolBuffers.Serialization ...@@ -92,7 +92,7 @@ namespace Google.ProtocolBuffers.Serialization
protected override bool Read(ref ulong value) protected override bool Read(ref ulong value)
{ {
string text = null; string text = null;
if (ReadAsText(ref text, typeof(ulong))) if (ReadAsText(ref text, typeof (ulong)))
{ {
value = XmlConvert.ToUInt64(text); value = XmlConvert.ToUInt64(text);
return true; return true;
...@@ -106,7 +106,7 @@ namespace Google.ProtocolBuffers.Serialization ...@@ -106,7 +106,7 @@ namespace Google.ProtocolBuffers.Serialization
protected override bool Read(ref float value) protected override bool Read(ref float value)
{ {
string text = null; string text = null;
if (ReadAsText(ref text, typeof(float))) if (ReadAsText(ref text, typeof (float)))
{ {
value = XmlConvert.ToSingle(text); value = XmlConvert.ToSingle(text);
return true; return true;
...@@ -120,7 +120,7 @@ namespace Google.ProtocolBuffers.Serialization ...@@ -120,7 +120,7 @@ namespace Google.ProtocolBuffers.Serialization
protected override bool Read(ref double value) protected override bool Read(ref double value)
{ {
string text = null; string text = null;
if (ReadAsText(ref text, typeof(double))) if (ReadAsText(ref text, typeof (double)))
{ {
value = XmlConvert.ToDouble(text); value = XmlConvert.ToDouble(text);
return true; return true;
...@@ -131,7 +131,10 @@ namespace Google.ProtocolBuffers.Serialization ...@@ -131,7 +131,10 @@ namespace Google.ProtocolBuffers.Serialization
/// <summary> /// <summary>
/// Provides decoding of bytes read from the input stream /// Provides decoding of bytes read from the input stream
/// </summary> /// </summary>
protected virtual ByteString DecodeBytes(string bytes) { return ByteString.FromBase64(bytes); } protected virtual ByteString DecodeBytes(string bytes)
{
return ByteString.FromBase64(bytes);
}
/// <summary> /// <summary>
/// Returns true if it was able to read a ByteString from the input /// Returns true if it was able to read a ByteString from the input
...@@ -139,7 +142,7 @@ namespace Google.ProtocolBuffers.Serialization ...@@ -139,7 +142,7 @@ namespace Google.ProtocolBuffers.Serialization
protected override bool Read(ref ByteString value) protected override bool Read(ref ByteString value)
{ {
string text = null; string text = null;
if (ReadAsText(ref text, typeof(ByteString))) if (ReadAsText(ref text, typeof (ByteString)))
{ {
value = DecodeBytes(text); value = DecodeBytes(text);
return true; return true;
...@@ -154,7 +157,7 @@ namespace Google.ProtocolBuffers.Serialization ...@@ -154,7 +157,7 @@ namespace Google.ProtocolBuffers.Serialization
protected override bool ReadEnum(ref object value) protected override bool ReadEnum(ref object value)
{ {
string text = null; string text = null;
if (ReadAsText(ref text, typeof(Enum))) if (ReadAsText(ref text, typeof (Enum)))
{ {
int number; int number;
if (int.TryParse(text, NumberStyles.Integer, CultureInfo.InvariantCulture, out number)) if (int.TryParse(text, NumberStyles.Integer, CultureInfo.InvariantCulture, out number))
......
...@@ -11,7 +11,10 @@ namespace Google.ProtocolBuffers.Serialization ...@@ -11,7 +11,10 @@ namespace Google.ProtocolBuffers.Serialization
/// <summary> /// <summary>
/// Encodes raw bytes to be written to the stream /// Encodes raw bytes to be written to the stream
/// </summary> /// </summary>
protected virtual string EncodeBytes(ByteString bytes) { return bytes.ToBase64(); } protected virtual string EncodeBytes(ByteString bytes)
{
return bytes.ToBase64();
}
/// <summary> /// <summary>
/// Writes a typed field as a text value /// Writes a typed field as a text value
...@@ -21,53 +24,83 @@ namespace Google.ProtocolBuffers.Serialization ...@@ -21,53 +24,83 @@ namespace Google.ProtocolBuffers.Serialization
/// <summary> /// <summary>
/// Writes a String value /// Writes a String value
/// </summary> /// </summary>
protected override void Write(string field, string value) { WriteAsText(field, value, value); } protected override void Write(string field, string value)
{
WriteAsText(field, value, value);
}
/// <summary> /// <summary>
/// Writes a Boolean value /// Writes a Boolean value
/// </summary> /// </summary>
protected override void Write(string field, bool value) { WriteAsText(field, XmlConvert.ToString(value), value); } protected override void Write(string field, bool value)
{
WriteAsText(field, XmlConvert.ToString(value), value);
}
/// <summary> /// <summary>
/// Writes a Int32 value /// Writes a Int32 value
/// </summary> /// </summary>
protected override void Write(string field, int value) { WriteAsText(field, XmlConvert.ToString(value), value); } protected override void Write(string field, int value)
{
WriteAsText(field, XmlConvert.ToString(value), value);
}
/// <summary> /// <summary>
/// Writes a UInt32 value /// Writes a UInt32 value
/// </summary> /// </summary>
[CLSCompliant(false)] [CLSCompliant(false)]
protected override void Write(string field, uint value) { WriteAsText(field, XmlConvert.ToString(value), value); } protected override void Write(string field, uint value)
{
WriteAsText(field, XmlConvert.ToString(value), value);
}
/// <summary> /// <summary>
/// Writes a Int64 value /// Writes a Int64 value
/// </summary> /// </summary>
protected override void Write(string field, long value) { WriteAsText(field, XmlConvert.ToString(value), value); } protected override void Write(string field, long value)
{
WriteAsText(field, XmlConvert.ToString(value), value);
}
/// <summary> /// <summary>
/// Writes a UInt64 value /// Writes a UInt64 value
/// </summary> /// </summary>
[CLSCompliant(false)] [CLSCompliant(false)]
protected override void Write(string field, ulong value) { WriteAsText(field, XmlConvert.ToString(value), value); } protected override void Write(string field, ulong value)
{
WriteAsText(field, XmlConvert.ToString(value), value);
}
/// <summary> /// <summary>
/// Writes a Single value /// Writes a Single value
/// </summary> /// </summary>
protected override void Write(string field, float value) { WriteAsText(field, XmlConvert.ToString(value), value); } protected override void Write(string field, float value)
{
WriteAsText(field, XmlConvert.ToString(value), value);
}
/// <summary> /// <summary>
/// Writes a Double value /// Writes a Double value
/// </summary> /// </summary>
protected override void Write(string field, double value) { WriteAsText(field, XmlConvert.ToString(value), value); } protected override void Write(string field, double value)
{
WriteAsText(field, XmlConvert.ToString(value), value);
}
/// <summary> /// <summary>
/// Writes a set of bytes /// Writes a set of bytes
/// </summary> /// </summary>
protected override void Write(string field, ByteString value) { WriteAsText(field, EncodeBytes(value), value); } protected override void Write(string field, ByteString value)
{
WriteAsText(field, EncodeBytes(value), value);
}
/// <summary> /// <summary>
/// Writes a System.Enum by the numeric and textual value /// Writes a System.Enum by the numeric and textual value
/// </summary> /// </summary>
protected override void WriteEnum(string field, int number, string name) { WriteAsText(field, name, number); } protected override void WriteEnum(string field, int number, string name)
{
WriteAsText(field, name, number);
}
} }
} }
\ No newline at end of file
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Text; using System.Globalization;
using Google.ProtocolBuffers.Descriptors; using Google.ProtocolBuffers.Descriptors;
namespace Google.ProtocolBuffers.Serialization namespace Google.ProtocolBuffers.Serialization
...@@ -54,19 +54,28 @@ namespace Google.ProtocolBuffers.Serialization ...@@ -54,19 +54,28 @@ namespace Google.ProtocolBuffers.Serialization
private bool GetValue<T>(ref T value) private bool GetValue<T>(ref T value)
{ {
if (!_ready) return false; if (!_ready)
{
return false;
}
object obj = _input.Current.Value; object obj = _input.Current.Value;
if (obj is T) if (obj is T)
value = (T)obj; {
value = (T) obj;
}
else else
{ {
try try
{ {
if (obj is IConvertible) if (obj is IConvertible)
value = (T)Convert.ChangeType(obj, typeof(T), System.Globalization.CultureInfo.InvariantCulture); {
value = (T) Convert.ChangeType(obj, typeof (T), CultureInfo.InvariantCulture);
}
else else
value = (T)obj; {
value = (T) obj;
}
} }
catch catch
{ {
...@@ -186,17 +195,21 @@ namespace Google.ProtocolBuffers.Serialization ...@@ -186,17 +195,21 @@ namespace Google.ProtocolBuffers.Serialization
object[] array = null; object[] array = null;
if (GetValue(ref array)) if (GetValue(ref array))
{ {
if (typeof(T) == typeof(ByteString)) if (typeof (T) == typeof (ByteString))
{ {
ICollection<ByteString> output = (ICollection<ByteString>)items; ICollection<ByteString> output = (ICollection<ByteString>) items;
foreach (byte[] item in array) foreach (byte[] item in array)
{
output.Add(ByteString.CopyFrom(item)); output.Add(ByteString.CopyFrom(item));
} }
}
else else
{ {
foreach (T item in array) foreach (T item in array)
{
items.Add(item); items.Add(item);
} }
}
return true; return true;
} }
return false; return false;
...@@ -208,13 +221,16 @@ namespace Google.ProtocolBuffers.Serialization ...@@ -208,13 +221,16 @@ namespace Google.ProtocolBuffers.Serialization
if (GetValue(ref array)) if (GetValue(ref array))
{ {
foreach (object item in array) foreach (object item in array)
{
items.Add(item); items.Add(item);
}
return true; return true;
} }
return false; return false;
} }
public override bool ReadMessageArray<T>(string field, ICollection<T> items, IMessageLite messageType, ExtensionRegistry registry) public override bool ReadMessageArray<T>(string field, ICollection<T> items, IMessageLite messageType,
ExtensionRegistry registry)
{ {
object[] array = null; object[] array = null;
if (GetValue(ref array)) if (GetValue(ref array))
...@@ -223,14 +239,17 @@ namespace Google.ProtocolBuffers.Serialization ...@@ -223,14 +239,17 @@ namespace Google.ProtocolBuffers.Serialization
{ {
IBuilderLite builder = messageType.WeakCreateBuilderForType(); IBuilderLite builder = messageType.WeakCreateBuilderForType();
new DictionaryReader(item).Merge(builder); new DictionaryReader(item).Merge(builder);
items.Add((T)builder.WeakBuild()); items.Add((T) builder.WeakBuild());
} }
return true; return true;
} }
return false; return false;
} }
public override bool ReadGroupArray<T>(string field, ICollection<T> items, IMessageLite messageType, ExtensionRegistry registry) public override bool ReadGroupArray<T>(string field, ICollection<T> items, IMessageLite messageType,
{ return ReadMessageArray(field, items, messageType, registry); } ExtensionRegistry registry)
{
return ReadMessageArray(field, items, messageType, registry);
}
} }
} }
\ No newline at end of file
using System; using System;
using System.Collections;
using System.Collections.Generic; using System.Collections.Generic;
using Google.ProtocolBuffers.Descriptors; using Google.ProtocolBuffers.Descriptors;
...@@ -15,8 +16,9 @@ namespace Google.ProtocolBuffers.Serialization ...@@ -15,8 +16,9 @@ namespace Google.ProtocolBuffers.Serialization
/// Constructs a writer using a new dictionary /// Constructs a writer using a new dictionary
/// </summary> /// </summary>
public DictionaryWriter() public DictionaryWriter()
: this(new Dictionary<string,object>(StringComparer.Ordinal)) : this(new Dictionary<string, object>(StringComparer.Ordinal))
{ } {
}
/// <summary> /// <summary>
/// Constructs a writer using an existing dictionary /// Constructs a writer using an existing dictionary
...@@ -38,7 +40,10 @@ namespace Google.ProtocolBuffers.Serialization ...@@ -38,7 +40,10 @@ namespace Google.ProtocolBuffers.Serialization
/// <summary> /// <summary>
/// Accesses the dictionary that is backing this writer /// Accesses the dictionary that is backing this writer
/// </summary> /// </summary>
public IDictionary<string, object> ToDictionary() { return _output; } public IDictionary<string, object> ToDictionary()
{
return _output;
}
/// <summary> /// <summary>
/// Writes the message to the the formatted stream. /// Writes the message to the the formatted stream.
...@@ -144,7 +149,7 @@ namespace Google.ProtocolBuffers.Serialization ...@@ -144,7 +149,7 @@ namespace Google.ProtocolBuffers.Serialization
/// <summary> /// <summary>
/// Writes an array of field values /// Writes an array of field values
/// </summary> /// </summary>
protected override void WriteArray(FieldType fieldType, string field, System.Collections.IEnumerable items) protected override void WriteArray(FieldType fieldType, string field, IEnumerable items)
{ {
List<object> objects = new List<object>(); List<object> objects = new List<object>();
foreach (object o in items) foreach (object o in items)
...@@ -155,18 +160,22 @@ namespace Google.ProtocolBuffers.Serialization ...@@ -155,18 +160,22 @@ namespace Google.ProtocolBuffers.Serialization
case FieldType.Message: case FieldType.Message:
{ {
DictionaryWriter writer = Create(); DictionaryWriter writer = Create();
writer.WriteMessage((IMessageLite)o); writer.WriteMessage((IMessageLite) o);
objects.Add(writer.ToDictionary()); objects.Add(writer.ToDictionary());
} }
break; break;
case FieldType.Bytes: case FieldType.Bytes:
objects.Add(((ByteString)o).ToByteArray()); objects.Add(((ByteString) o).ToByteArray());
break; break;
case FieldType.Enum: case FieldType.Enum:
if (o is IEnumLite) if (o is IEnumLite)
objects.Add(((IEnumLite)o).Number); {
objects.Add(((IEnumLite) o).Number);
}
else else
objects.Add((int)o); {
objects.Add((int) o);
}
break; break;
default: default:
objects.Add(o); objects.Add(o);
......
...@@ -13,28 +13,51 @@ namespace Google.ProtocolBuffers.Serialization ...@@ -13,28 +13,51 @@ namespace Google.ProtocolBuffers.Serialization
private readonly JsonCursor _input; private readonly JsonCursor _input;
private readonly Stack<int> _stopChar; private readonly Stack<int> _stopChar;
enum ReaderState { Start, BeginValue, EndValue, BeginObject, BeginArray } private enum ReaderState
string _current; {
ReaderState _state; Start,
BeginValue,
EndValue,
BeginObject,
BeginArray
}
private string _current;
private ReaderState _state;
/// <summary> /// <summary>
/// Constructs a JsonFormatReader to parse Json into a message, this method does not use text encoding, all bytes MUST /// Constructs a JsonFormatReader to parse Json into a message, this method does not use text encoding, all bytes MUST
/// represent ASCII character values. /// represent ASCII character values.
/// </summary> /// </summary>
public static JsonFormatReader CreateInstance(Stream stream) { return new JsonFormatReader(JsonCursor.CreateInstance(stream)); } public static JsonFormatReader CreateInstance(Stream stream)
{
return new JsonFormatReader(JsonCursor.CreateInstance(stream));
}
/// <summary> /// <summary>
/// Constructs a JsonFormatReader to parse Json into a message, this method does not use text encoding, all bytes MUST /// Constructs a JsonFormatReader to parse Json into a message, this method does not use text encoding, all bytes MUST
/// represent ASCII character values. /// represent ASCII character values.
/// </summary> /// </summary>
public static JsonFormatReader CreateInstance(byte[] bytes) { return new JsonFormatReader(JsonCursor.CreateInstance(bytes)); } public static JsonFormatReader CreateInstance(byte[] bytes)
{
return new JsonFormatReader(JsonCursor.CreateInstance(bytes));
}
/// <summary> /// <summary>
/// Constructs a JsonFormatReader to parse Json into a message /// Constructs a JsonFormatReader to parse Json into a message
/// </summary> /// </summary>
public static JsonFormatReader CreateInstance(string jsonText) { return new JsonFormatReader(JsonCursor.CreateInstance(jsonText)); } public static JsonFormatReader CreateInstance(string jsonText)
{
return new JsonFormatReader(JsonCursor.CreateInstance(jsonText));
}
/// <summary> /// <summary>
/// Constructs a JsonFormatReader to parse Json into a message /// Constructs a JsonFormatReader to parse Json into a message
/// </summary> /// </summary>
public static JsonFormatReader CreateInstance(TextReader input) { return new JsonFormatReader(JsonCursor.CreateInstance(input)); } public static JsonFormatReader CreateInstance(TextReader input)
{
return new JsonFormatReader(JsonCursor.CreateInstance(input));
}
/// <summary> /// <summary>
/// Constructs a JsonFormatReader to parse Json into a message /// Constructs a JsonFormatReader to parse Json into a message
...@@ -52,12 +75,16 @@ namespace Google.ProtocolBuffers.Serialization ...@@ -52,12 +75,16 @@ namespace Google.ProtocolBuffers.Serialization
/// </summary> /// </summary>
protected JsonFormatReader(TextReader input) protected JsonFormatReader(TextReader input)
: this(JsonCursor.CreateInstance(input)) : this(JsonCursor.CreateInstance(input))
{ } {
}
/// <summary> /// <summary>
/// Returns true if the reader is currently on an array element /// Returns true if the reader is currently on an array element
/// </summary> /// </summary>
public bool IsArrayMessage { get { return _input.NextChar == '['; } } public bool IsArrayMessage
{
get { return _input.NextChar == '['; }
}
/// <summary> /// <summary>
/// Returns an enumerator that is used to cursor over an array of messages /// Returns an enumerator that is used to cursor over an array of messages
...@@ -68,8 +95,10 @@ namespace Google.ProtocolBuffers.Serialization ...@@ -68,8 +95,10 @@ namespace Google.ProtocolBuffers.Serialization
public IEnumerable<JsonFormatReader> EnumerateArray() public IEnumerable<JsonFormatReader> EnumerateArray()
{ {
foreach (string ignored in ForeachArrayItem(_current)) foreach (string ignored in ForeachArrayItem(_current))
{
yield return this; yield return this;
} }
}
/// <summary> /// <summary>
/// Merges the contents of stream into the provided message builder /// Merges the contents of stream into the provided message builder
...@@ -81,7 +110,7 @@ namespace Google.ProtocolBuffers.Serialization ...@@ -81,7 +110,7 @@ namespace Google.ProtocolBuffers.Serialization
_state = ReaderState.BeginObject; _state = ReaderState.BeginObject;
builder.WeakMergeFrom(this, registry); builder.WeakMergeFrom(this, registry);
_input.Consume((char)_stopChar.Pop()); _input.Consume((char) _stopChar.Pop());
_state = ReaderState.EndValue; _state = ReaderState.EndValue;
return builder; return builder;
} }
...@@ -106,18 +135,24 @@ namespace Google.ProtocolBuffers.Serialization ...@@ -106,18 +135,24 @@ namespace Google.ProtocolBuffers.Serialization
protected override bool PeekNext(out string field) protected override bool PeekNext(out string field)
{ {
field = _current; field = _current;
if(_state == ReaderState.BeginValue) if (_state == ReaderState.BeginValue)
{
return true; return true;
}
int next = _input.NextChar; int next = _input.NextChar;
if (next == _stopChar.Peek()) if (next == _stopChar.Peek())
{
return false; return false;
}
_input.Assert(next != -1, "Unexpected end of file."); _input.Assert(next != -1, "Unexpected end of file.");
//not sure about this yet, it will allow {, "a":true } //not sure about this yet, it will allow {, "a":true }
if (_state == ReaderState.EndValue && !_input.TryConsume(',')) if (_state == ReaderState.EndValue && !_input.TryConsume(','))
{
return false; return false;
}
field = _current = _input.ReadString(); field = _current = _input.ReadString();
_input.Consume(':'); _input.Consume(':');
...@@ -134,19 +169,31 @@ namespace Google.ProtocolBuffers.Serialization ...@@ -134,19 +169,31 @@ namespace Google.ProtocolBuffers.Serialization
JsonCursor.JsType type = _input.ReadVariant(out temp); JsonCursor.JsType type = _input.ReadVariant(out temp);
_state = ReaderState.EndValue; _state = ReaderState.EndValue;
_input.Assert(type != JsonCursor.JsType.Array && type != JsonCursor.JsType.Object, "Encountered {0} while expecting {1}", type, typeInfo); _input.Assert(type != JsonCursor.JsType.Array && type != JsonCursor.JsType.Object,
"Encountered {0} while expecting {1}", type, typeInfo);
if (type == JsonCursor.JsType.Null) if (type == JsonCursor.JsType.Null)
{
return false; return false;
if (type == JsonCursor.JsType.True) value = "1"; }
else if (type == JsonCursor.JsType.False) value = "0"; if (type == JsonCursor.JsType.True)
else value = temp as string; {
value = "1";
}
else if (type == JsonCursor.JsType.False)
{
value = "0";
}
else
{
value = temp as string;
}
//exponent representation of integer number: //exponent representation of integer number:
if (value != null && type == JsonCursor.JsType.Number && if (value != null && type == JsonCursor.JsType.Number &&
(typeInfo != typeof(double) && typeInfo != typeof(float)) && (typeInfo != typeof (double) && typeInfo != typeof (float)) &&
value.IndexOf("e", StringComparison.OrdinalIgnoreCase) > 0) value.IndexOf("e", StringComparison.OrdinalIgnoreCase) > 0)
{ {
value = XmlConvert.ToString((long)Math.Round(XmlConvert.ToDouble(value), 0)); value = XmlConvert.ToString((long) Math.Round(XmlConvert.ToDouble(value), 0));
} }
return value != null; return value != null;
} }
...@@ -177,10 +224,12 @@ namespace Google.ProtocolBuffers.Serialization ...@@ -177,10 +224,12 @@ namespace Google.ProtocolBuffers.Serialization
{ {
_current = field; _current = field;
yield return field; yield return field;
if(!_input.TryConsume(',')) if (!_input.TryConsume(','))
{
break; break;
} }
_input.Consume((char)_stopChar.Pop()); }
_input.Consume((char) _stopChar.Pop());
_state = ReaderState.EndValue; _state = ReaderState.EndValue;
} }
...@@ -192,6 +241,5 @@ namespace Google.ProtocolBuffers.Serialization ...@@ -192,6 +241,5 @@ namespace Google.ProtocolBuffers.Serialization
Merge(builder, registry); Merge(builder, registry);
return true; return true;
} }
} }
} }
\ No newline at end of file
...@@ -2,7 +2,6 @@ ...@@ -2,7 +2,6 @@
using System.Collections.Generic; using System.Collections.Generic;
using System.IO; using System.IO;
using System.Xml; using System.Xml;
using Google.ProtocolBuffers.Descriptors;
namespace Google.ProtocolBuffers.Serialization namespace Google.ProtocolBuffers.Serialization
{ {
...@@ -17,31 +16,55 @@ namespace Google.ProtocolBuffers.Serialization ...@@ -17,31 +16,55 @@ namespace Google.ProtocolBuffers.Serialization
private readonly XmlReader _input; private readonly XmlReader _input;
private string _rootElementName; private string _rootElementName;
static XmlReaderSettings DefaultSettings private static XmlReaderSettings DefaultSettings
{ {
get { return new XmlReaderSettings() { CheckCharacters=false, IgnoreComments=true, IgnoreProcessingInstructions = true }; } get
{
return new XmlReaderSettings()
{CheckCharacters = false, IgnoreComments = true, IgnoreProcessingInstructions = true};
}
} }
/// <summary> /// <summary>
/// Constructs the XmlFormatReader using the stream provided as the xml /// Constructs the XmlFormatReader using the stream provided as the xml
/// </summary> /// </summary>
public static XmlFormatReader CreateInstance(byte[] input) { return new XmlFormatReader(XmlReader.Create(new MemoryStream(input, false), DefaultSettings)); } public static XmlFormatReader CreateInstance(byte[] input)
{
return new XmlFormatReader(XmlReader.Create(new MemoryStream(input, false), DefaultSettings));
}
/// <summary> /// <summary>
/// Constructs the XmlFormatReader using the stream provided as the xml /// Constructs the XmlFormatReader using the stream provided as the xml
/// </summary> /// </summary>
public static XmlFormatReader CreateInstance(Stream input) { return new XmlFormatReader(XmlReader.Create(input, DefaultSettings)); } public static XmlFormatReader CreateInstance(Stream input)
{
return new XmlFormatReader(XmlReader.Create(input, DefaultSettings));
}
/// <summary> /// <summary>
/// Constructs the XmlFormatReader using the string provided as the xml to be read /// Constructs the XmlFormatReader using the string provided as the xml to be read
/// </summary> /// </summary>
public static XmlFormatReader CreateInstance(String input) { return new XmlFormatReader(XmlReader.Create(new StringReader(input), DefaultSettings)); } public static XmlFormatReader CreateInstance(String input)
{
return new XmlFormatReader(XmlReader.Create(new StringReader(input), DefaultSettings));
}
/// <summary> /// <summary>
/// Constructs the XmlFormatReader using the xml in the TextReader /// Constructs the XmlFormatReader using the xml in the TextReader
/// </summary> /// </summary>
public static XmlFormatReader CreateInstance(TextReader input) { return new XmlFormatReader(XmlReader.Create(input, DefaultSettings)); } public static XmlFormatReader CreateInstance(TextReader input)
{
return new XmlFormatReader(XmlReader.Create(input, DefaultSettings));
}
/// <summary> /// <summary>
/// Constructs the XmlFormatReader with the XmlReader /// Constructs the XmlFormatReader with the XmlReader
/// </summary> /// </summary>
public static XmlFormatReader CreateInstance(XmlReader input) { return new XmlFormatReader(input); } public static XmlFormatReader CreateInstance(XmlReader input)
{
return new XmlFormatReader(input);
}
/// <summary> /// <summary>
/// Constructs the XmlFormatReader with the XmlReader and options /// Constructs the XmlFormatReader with the XmlReader and options
/// </summary> /// </summary>
...@@ -56,10 +79,15 @@ namespace Google.ProtocolBuffers.Serialization ...@@ -56,10 +79,15 @@ namespace Google.ProtocolBuffers.Serialization
/// Gets or sets the options to use when reading the xml /// Gets or sets the options to use when reading the xml
/// </summary> /// </summary>
public XmlReaderOptions Options { get; set; } public XmlReaderOptions Options { get; set; }
/// <summary> /// <summary>
/// Sets the options to use while generating the XML /// Sets the options to use while generating the XML
/// </summary> /// </summary>
public XmlFormatReader SetOptions(XmlReaderOptions options) { Options = options; return this; } public XmlFormatReader SetOptions(XmlReaderOptions options)
{
Options = options;
return this;
}
/// <summary> /// <summary>
/// Gets or sets the default element name to use when using the Merge&lt;TBuilder>() /// Gets or sets the default element name to use when using the Merge&lt;TBuilder>()
...@@ -67,7 +95,11 @@ namespace Google.ProtocolBuffers.Serialization ...@@ -67,7 +95,11 @@ namespace Google.ProtocolBuffers.Serialization
public string RootElementName public string RootElementName
{ {
get { return _rootElementName; } get { return _rootElementName; }
set { ThrowHelper.ThrowIfNull(value, "RootElementName"); _rootElementName = value; } set
{
ThrowHelper.ThrowIfNull(value, "RootElementName");
_rootElementName = value;
}
} }
private XmlFormatReader CloneWith(XmlReader rdr) private XmlFormatReader CloneWith(XmlReader rdr)
...@@ -76,34 +108,45 @@ namespace Google.ProtocolBuffers.Serialization ...@@ -76,34 +108,45 @@ namespace Google.ProtocolBuffers.Serialization
copy._rootElementName = _rootElementName; copy._rootElementName = _rootElementName;
copy.Depth = Depth; copy.Depth = Depth;
return copy; return copy;
} }
private void NextElement() private void NextElement()
{ {
while (!_input.IsStartElement() && _input.Read()) while (!_input.IsStartElement() && _input.Read())
{
continue; continue;
} }
}
private static void Assert(bool cond) private static void Assert(bool cond)
{ {
if (!cond) throw new FormatException(); if (!cond)
{
throw new FormatException();
}
} }
/// <summary> /// <summary>
/// Merge the provided builder as an element named <see cref="RootElementName"/> in the current context /// Merge the provided builder as an element named <see cref="RootElementName"/> in the current context
/// </summary> /// </summary>
public override TBuilder Merge<TBuilder>(TBuilder builder, ExtensionRegistry registry) public override TBuilder Merge<TBuilder>(TBuilder builder, ExtensionRegistry registry)
{ return Merge(_rootElementName, builder, registry); } {
return Merge(_rootElementName, builder, registry);
}
/// <summary> /// <summary>
/// Merge the provided builder as an element of the current context /// Merge the provided builder as an element of the current context
/// </summary> /// </summary>
public TBuilder Merge<TBuilder>(string element, TBuilder builder) where TBuilder : IBuilderLite public TBuilder Merge<TBuilder>(string element, TBuilder builder) where TBuilder : IBuilderLite
{ return Merge(element, builder, ExtensionRegistry.Empty); } {
return Merge(element, builder, ExtensionRegistry.Empty);
}
/// <summary> /// <summary>
/// Merge the provided builder as an element of the current context /// Merge the provided builder as an element of the current context
/// </summary> /// </summary>
public TBuilder Merge<TBuilder>(string element, TBuilder builder, ExtensionRegistry registry) where TBuilder : IBuilderLite public TBuilder Merge<TBuilder>(string element, TBuilder builder, ExtensionRegistry registry)
where TBuilder : IBuilderLite
{ {
string field; string field;
Assert(PeekNext(out field) && field == element); Assert(PeekNext(out field) && field == element);
...@@ -121,7 +164,7 @@ namespace Google.ProtocolBuffers.Serialization ...@@ -121,7 +164,7 @@ namespace Google.ProtocolBuffers.Serialization
protected override bool PeekNext(out string field) protected override bool PeekNext(out string field)
{ {
NextElement(); NextElement();
if(_input.IsStartElement()) if (_input.IsStartElement())
{ {
field = _input.LocalName; field = _input.LocalName;
return true; return true;
...@@ -141,8 +184,10 @@ namespace Google.ProtocolBuffers.Serialization ...@@ -141,8 +184,10 @@ namespace Google.ProtocolBuffers.Serialization
{ {
int depth = _input.Depth; int depth = _input.Depth;
while (_input.Depth >= depth && _input.NodeType != XmlNodeType.EndElement) while (_input.Depth >= depth && _input.NodeType != XmlNodeType.EndElement)
{
Assert(_input.Read()); Assert(_input.Read());
} }
}
_input.Read(); _input.Read();
} }
} }
...@@ -187,7 +232,9 @@ namespace Google.ProtocolBuffers.Serialization ...@@ -187,7 +232,9 @@ namespace Google.ProtocolBuffers.Serialization
int depth = _input.Depth; int depth = _input.Depth;
XmlReader child = _input.ReadSubtree(); XmlReader child = _input.ReadSubtree();
while (!child.IsStartElement() && child.Read()) while (!child.IsStartElement() && child.Read())
{
continue; continue;
}
child.Read(); child.Read();
builder.WeakMergeFrom(CloneWith(child), registry); builder.WeakMergeFrom(CloneWith(child), registry);
Assert(depth == _input.Depth && _input.NodeType == XmlNodeType.EndElement); Assert(depth == _input.Depth && _input.NodeType == XmlNodeType.EndElement);
...@@ -211,7 +258,9 @@ namespace Google.ProtocolBuffers.Serialization ...@@ -211,7 +258,9 @@ namespace Google.ProtocolBuffers.Serialization
if (!isNested) if (!isNested)
{ {
foreach (string item in NonNestedArrayItems(field)) foreach (string item in NonNestedArrayItems(field))
{
yield return item; yield return item;
}
yield break; yield break;
} }
if (!_input.IsEmptyElement) if (!_input.IsEmptyElement)
...@@ -220,11 +269,15 @@ namespace Google.ProtocolBuffers.Serialization ...@@ -220,11 +269,15 @@ namespace Google.ProtocolBuffers.Serialization
XmlReader child = _input.ReadSubtree(); XmlReader child = _input.ReadSubtree();
while (!child.IsStartElement() && child.Read()) while (!child.IsStartElement() && child.Read())
{
continue; continue;
}
child.Read(); child.Read();
foreach (string item in CloneWith(child).NonNestedArrayItems("item")) foreach (string item in CloneWith(child).NonNestedArrayItems("item"))
{
yield return item; yield return item;
}
Assert(depth == _input.Depth && _input.NodeType == XmlNodeType.EndElement); Assert(depth == _input.Depth && _input.NodeType == XmlNodeType.EndElement);
} }
_input.Read(); _input.Read();
......
...@@ -10,6 +10,7 @@ namespace Google.ProtocolBuffers.Serialization ...@@ -10,6 +10,7 @@ namespace Google.ProtocolBuffers.Serialization
{ {
/// <summary> Simple xml formatting with no attributes </summary> /// <summary> Simple xml formatting with no attributes </summary>
None, None,
/// <summary> Requires that arrays items are nested in an &lt;item> element </summary> /// <summary> Requires that arrays items are nested in an &lt;item> element </summary>
ReadNestedArrays = 1, ReadNestedArrays = 1,
} }
......
...@@ -10,10 +10,13 @@ namespace Google.ProtocolBuffers.Serialization ...@@ -10,10 +10,13 @@ namespace Google.ProtocolBuffers.Serialization
{ {
/// <summary> Simple xml formatting with no attributes </summary> /// <summary> Simple xml formatting with no attributes </summary>
None, None,
/// <summary> Writes the 'value' attribute on all enumerations with the numeric identifier </summary> /// <summary> Writes the 'value' attribute on all enumerations with the numeric identifier </summary>
OutputEnumValues = 0x1, OutputEnumValues = 0x1,
/// <summary> Embeds array items into child &lt;item> elements </summary> /// <summary> Embeds array items into child &lt;item> elements </summary>
OutputNestedArrays = 0x4, OutputNestedArrays = 0x4,
/// <summary> Outputs the 'type' attribute for compatibility with the <see cref="System.Runtime.Serialization.Json.JsonReaderWriterFactory">JsonReaderWriterFactory</see> </summary> /// <summary> Outputs the 'type' attribute for compatibility with the <see cref="System.Runtime.Serialization.Json.JsonReaderWriterFactory">JsonReaderWriterFactory</see> </summary>
/// <remarks> This option must, by nessessity, also enable NestedArrayItems </remarks> /// <remarks> This option must, by nessessity, also enable NestedArrayItems </remarks>
OutputJsonTypes = 0x8, OutputJsonTypes = 0x8,
......
...@@ -35,12 +35,12 @@ ...@@ -35,12 +35,12 @@
#endregion #endregion
using System; using System;
using System.Collections;
using System.Collections.Generic; using System.Collections.Generic;
using System.Globalization; using System.Globalization;
using System.IO; using System.IO;
using System.Text; using System.Text;
using Google.ProtocolBuffers.Descriptors; using Google.ProtocolBuffers.Descriptors;
using System.Collections;
namespace Google.ProtocolBuffers namespace Google.ProtocolBuffers
{ {
...@@ -170,10 +170,10 @@ namespace Google.ProtocolBuffers ...@@ -170,10 +170,10 @@ namespace Google.ProtocolBuffers
// the double to/from string will trim the precision to 6 places. As with other numeric formats // the double to/from string will trim the precision to 6 places. As with other numeric formats
// below, always use the invariant culture so it's predictable. // below, always use the invariant culture so it's predictable.
case FieldType.Float: case FieldType.Float:
generator.Print(((float)value).ToString("r", CultureInfo.InvariantCulture)); generator.Print(((float) value).ToString("r", CultureInfo.InvariantCulture));
break; break;
case FieldType.Double: case FieldType.Double:
generator.Print(((double)value).ToString("r", CultureInfo.InvariantCulture)); generator.Print(((double) value).ToString("r", CultureInfo.InvariantCulture));
break; break;
case FieldType.Int32: case FieldType.Int32:
...@@ -756,8 +756,10 @@ namespace Google.ProtocolBuffers ...@@ -756,8 +756,10 @@ namespace Google.ProtocolBuffers
{ {
subBuilder = extension.DefaultInstance.WeakCreateBuilderForType() as IBuilder; subBuilder = extension.DefaultInstance.WeakCreateBuilderForType() as IBuilder;
if (subBuilder == null) if (subBuilder == null)
{
throw new NotSupportedException("Lite messages are not supported."); throw new NotSupportedException("Lite messages are not supported.");
} }
}
while (!tokenizer.TryConsume(endToken)) while (!tokenizer.TryConsume(endToken))
{ {
......
This diff is collapsed.
...@@ -143,6 +143,7 @@ namespace Google.ProtocolBuffers ...@@ -143,6 +143,7 @@ namespace Google.ProtocolBuffers
} }
#endif #endif
/// <summary> /// <summary>
/// Converts a field type to its wire type. Done with a switch for the sake /// Converts a field type to its wire type. Done with a switch for the sake
/// of speed - this is significantly faster than a dictionary lookup. /// of speed - this is significantly faster than a dictionary lookup.
......
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