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