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)
{
......@@ -70,7 +74,7 @@ namespace Google.ProtocolBuffers.ProtoGen
protected bool HasDefaultValue
{
get
get
{
switch (Descriptor.FieldType)
{
......@@ -141,20 +145,32 @@ 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;
}
......@@ -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("}");
}
......
This diff is collapsed.
......@@ -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)
{
......@@ -154,7 +154,7 @@ namespace Google.ProtocolBuffers.ProtoGen
foreach (string path in searchPath)
{
string exeFile = Path.Combine(path, ProtocExecutable);
string exeFile = Path.Combine(path, ProtocExecutable);
if (File.Exists(exeFile))
{
return exeFile;
......
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" : "";
......
......@@ -44,16 +44,16 @@ namespace Google.ProtocolBuffers.ProtoGen
internal static class SourceGenerators
{
private static readonly Dictionary<Type, Func<IDescriptor, ISourceGenerator>> GeneratorFactories =
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)},
// For other fields, we have IFieldSourceGenerators.
{typeof(FieldDescriptor),descriptor=>new ExtensionGenerator((FieldDescriptor)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)}
};
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,7 +111,9 @@ 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
{
......@@ -102,16 +99,18 @@ namespace Google.ProtocolBuffers
{
items = new SortedList<int, IEnumLite>();
#if SILVERLIGHT2
// Silverlight doesn't support Enum.GetValues
// TODO(jonskeet): Validate that this reflection is permitted, e.g. in Windows Phone 7
// Silverlight doesn't support Enum.GetValues
// TODO(jonskeet): Validate that this reflection is permitted, e.g. in Windows Phone 7
foreach (FieldInfo fi in typeof (TEnum).GetFields(BindingFlags.Static | BindingFlags.Public))
{
TEnum evalue = (TEnum) fi.GetValue(null);
items.Add(Convert.ToInt32(evalue), new EnumValue(evalue));
}
#else
foreach (TEnum evalue in Enum.GetValues(typeof(TEnum)))
items.Add(Convert.ToInt32(evalue), new EnumValue(evalue));
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;
......@@ -153,9 +155,9 @@ namespace Google.ProtocolBuffers
{
return input.SkipField();
}
WireFormat.WireType expectedType = field.IsPacked
? WireFormat.WireType.LengthDelimited
: WireFormat.GetWireType(field.FieldType);
WireFormat.WireType expectedType = field.IsPacked
? WireFormat.WireType.LengthDelimited
: WireFormat.GetWireType(field.FieldType);
if (wireType != expectedType)
{
expectedType = WireFormat.GetWireType(field.FieldType);
......@@ -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,22 +192,34 @@ 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();
}
else
{
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,7 +231,9 @@ namespace Google.ProtocolBuffers
object unknown;
IEnumLite value = null;
if (input.ReadEnum(ref value, out unknown, field.EnumType))
{
extensions[field] = value;
}
}
else
{
......@@ -221,7 +242,9 @@ namespace Google.ProtocolBuffers
input.ReadEnumArray(tag, fieldName, list, out unknown, field.EnumType);
foreach (IEnumLite en in list)
{
extensions.AddRepeatedField(field, en);
}
}
break;
}
......@@ -231,14 +254,18 @@ 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,7 +83,9 @@ namespace Google.ProtocolBuffers
if (entry.Key.IsRepeated)
{
foreach (object o in ((IEnumerable) entry.Value))
{
PrintField(fn, true, o, writer);
}
}
else
{
......
......@@ -34,9 +34,9 @@
#endregion
using System;
using System.Collections.Generic;
using Google.ProtocolBuffers.Descriptors;
using System;
namespace Google.ProtocolBuffers
{
......@@ -107,7 +107,9 @@ namespace Google.ProtocolBuffers
foreach (IGeneratedExtensionLite ext in extensionsByNumber.Values)
{
if (StringComparer.Ordinal.Equals(ext.Descriptor.FullName, fullName))
{
return ext as ExtensionInfo;
}
}
return null;
}
......@@ -204,7 +206,9 @@ namespace Google.ProtocolBuffers
// up by type name.
Dictionary<string, IGeneratedExtensionLite> map;
if (extensionsByName.TryGetValue(liteExtension.ContainingType, out map))
{
map[field.MessageType.FullName] = extension;
}
}
}
}
......
......@@ -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)
......
......@@ -144,17 +144,19 @@ namespace Google.ProtocolBuffers
}
#if !LITE
/// <summary>
/// Force coercion to full descriptor dictionary.
/// </summary>
internal IDictionary<Descriptors.FieldDescriptor, object> AllFieldDescriptors
/// <summary>
/// Force coercion to full descriptor dictionary.
/// </summary>
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);
}
}
......@@ -390,13 +392,15 @@ namespace Google.ProtocolBuffers
}
#if !LITE
/// <summary>
/// See <see cref="IBuilder{TMessage, TBuilder}.MergeFrom(IMessageLite)" />
/// </summary>
/// <summary>
/// See <see cref="IBuilder{TMessage, TBuilder}.MergeFrom(IMessageLite)" />
/// </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
......@@ -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
......@@ -76,12 +74,14 @@ namespace Google.ProtocolBuffers
public string Name
{
get
get
{
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(string rootElementName, System.Xml.XmlReader reader)
{ return ParseFromXml(rootElementName, reader, ExtensionRegistry.Empty); }
public static TMessage ParseFromXml(XmlReader reader)
{
return ParseFromXml(XmlFormatReader.DefaultRootElementName, 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
......
......@@ -115,7 +115,7 @@ namespace Google.ProtocolBuffers
/// Reads a group field value from the stream.
/// </summary>
void ReadGroup(int fieldNumber, IBuilderLite builder,
ExtensionRegistry extensionRegistry);
ExtensionRegistry extensionRegistry);
/// <summary>
/// Reads a group field value from the stream and merges it into the given
......@@ -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,67 +134,71 @@ 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;
void WriteMessageArray<T>(int fieldNumber, string fieldName, IEnumerable<T> list)
where T : IMessageLite;
void WriteStringArray(int fieldNumber, string fieldName, IEnumerable<string> list);
void WriteBytesArray(int fieldNumber, string fieldName, IEnumerable<ByteString> list);
void WriteBoolArray(int fieldNumber, string fieldName, IEnumerable<bool> list);
void WriteInt32Array(int fieldNumber, string fieldName, IEnumerable<int> list);
void WriteSInt32Array(int fieldNumber, string fieldName, IEnumerable<int> list);
void WriteUInt32Array(int fieldNumber, string fieldName, IEnumerable<uint> list);
void WriteFixed32Array(int fieldNumber, string fieldName, IEnumerable<uint> list);
void WriteSFixed32Array(int fieldNumber, string fieldName, IEnumerable<int> list);
void WriteInt64Array(int fieldNumber, string fieldName, IEnumerable<long> list);
void WriteSInt64Array(int fieldNumber, string fieldName, IEnumerable<long> list);
void WriteUInt64Array(int fieldNumber, string fieldName, IEnumerable<ulong> list);
void WriteFixed64Array(int fieldNumber, string fieldName, IEnumerable<ulong> list);
void WriteSFixed64Array(int fieldNumber, string fieldName, IEnumerable<long> list);
void WriteDoubleArray(int fieldNumber, string fieldName, IEnumerable<double> list);
void WriteFloatArray(int fieldNumber, string fieldName, IEnumerable<float> list);
[CLSCompliant(false)]
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;
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 WritePackedInt32Array(int fieldNumber, string fieldName, int calculatedSize, IEnumerable<int> 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,23 +54,32 @@ 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
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
{
_ready = _input.MoveNext();
_ready = _input.MoveNext();
return false;
}
}
......@@ -83,7 +92,7 @@ namespace Google.ProtocolBuffers.Serialization
/// </summary>
protected override bool Read(ref bool value)
{
return GetValue(ref value);
return GetValue(ref value);
}
/// <summary>
......@@ -186,35 +195,42 @@ 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;
}
public override bool ReadEnumArray(string field, ICollection<object> items)
{
object[] array = null;
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,9 +40,12 @@ 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>
/// <summary>
/// Writes the message to the the formatted stream.
/// </summary>
public override void WriteMessage(IMessageLite message)
......@@ -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);
......@@ -177,4 +186,4 @@ namespace Google.ProtocolBuffers.Serialization
_output[field] = objects.ToArray();
}
}
}
}
\ No newline at end of file
......@@ -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,7 +95,9 @@ namespace Google.ProtocolBuffers.Serialization
public IEnumerable<JsonFormatReader> EnumerateArray()
{
foreach (string ignored in ForeachArrayItem(_current))
{
yield return this;
}
}
/// <summary>
......@@ -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
......@@ -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
{
......@@ -166,14 +166,14 @@ namespace Google.ProtocolBuffers
{
switch (field.FieldType)
{
// The Float and Double types must specify the "r" format to preserve their precision, otherwise,
// 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.
// The Float and Double types must specify the "r" format to preserve their precision, otherwise,
// 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,7 +756,9 @@ 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