Switched from ProtoBuff to NetSerializer

NetSerializer should be slightly faster than Protocol Buffers
This commit is contained in:
MaxXor 2015-08-08 16:21:09 +02:00
parent 0a9f3d0dd7
commit 23cafeb2f3
300 changed files with 3728 additions and 41235 deletions

View File

@ -56,6 +56,17 @@
<Compile Include="Core\Helper\NativeMethodsHelper.cs" />
<Compile Include="Core\Helper\PlatformHelper.cs" />
<Compile Include="Core\Helper\ScreenHelper.cs" />
<Compile Include="Core\NetSerializer\CodeGenContext.cs" />
<Compile Include="Core\NetSerializer\Helpers.cs" />
<Compile Include="Core\NetSerializer\ITypeSerializer.cs" />
<Compile Include="Core\NetSerializer\Primitives.cs" />
<Compile Include="Core\NetSerializer\Serializer.cs" />
<Compile Include="Core\NetSerializer\TypeSerializers\ArraySerializer.cs" />
<Compile Include="Core\NetSerializer\TypeSerializers\DictionarySerializer.cs" />
<Compile Include="Core\NetSerializer\TypeSerializers\EnumSerializer.cs" />
<Compile Include="Core\NetSerializer\TypeSerializers\GenericSerializer.cs" />
<Compile Include="Core\NetSerializer\TypeSerializers\ObjectSerializer.cs" />
<Compile Include="Core\NetSerializer\TypeSerializers\PrimitivesSerializer.cs" />
<Compile Include="Core\Networking\Client.cs" />
<Compile Include="Core\Commands\CommandHandler.cs" />
<Compile Include="Core\Commands\ConnectionHandler.cs" />
@ -164,13 +175,6 @@
<Compile Include="Core\Packets\ServerPackets\DoMouseEvent.cs" />
<Compile Include="Core\Packets\ServerPackets\DoProcessStart.cs" />
<Compile Include="Core\Packets\ServerPackets\GetProcesses.cs" />
<Compile Include="Core\ProtoBuf\CallbackAttributes.cs" />
<Compile Include="Core\ProtoBuf\Extensible.cs" />
<Compile Include="Core\ProtoBuf\ExtensibleUtil.cs" />
<Compile Include="Core\ProtoBuf\GlobalSuppressions.cs" />
<Compile Include="Core\ProtoBuf\KeyValuePairProxy.cs" />
<Compile Include="Core\ProtoBuf\ProtoConverterAttribute.cs" />
<Compile Include="Core\ProtoBuf\Serializers\ImmutableCollectionDecorator.cs" />
<Compile Include="Core\Utilities\Shell.cs" />
<Compile Include="Core\Recovery\Browsers\Chrome.cs" />
<Compile Include="Core\Recovery\Browsers\Firefox.cs" />
@ -196,84 +200,6 @@
<Compile Include="Core\Packets\ServerPackets\DoClientUninstall.cs" />
<Compile Include="Core\Packets\ServerPackets\GetAuthentication.cs" />
<Compile Include="Core\Packets\ServerPackets\DoClientReconnect.cs" />
<Compile Include="Core\Packets\UnknownPacket.cs" />
<Compile Include="Core\ProtoBuf\BclHelpers.cs" />
<Compile Include="Core\ProtoBuf\BufferExtension.cs" />
<Compile Include="Core\ProtoBuf\BufferPool.cs" />
<Compile Include="Core\ProtoBuf\DataFormat.cs" />
<Compile Include="Core\ProtoBuf\Helpers.cs" />
<Compile Include="Core\ProtoBuf\IExtensible.cs" />
<Compile Include="Core\ProtoBuf\IExtension.cs" />
<Compile Include="Core\ProtoBuf\ImplicitFields.cs" />
<Compile Include="Core\ProtoBuf\Meta\AttributeMap.cs" />
<Compile Include="Core\ProtoBuf\Meta\BasicList.cs" />
<Compile Include="Core\ProtoBuf\Meta\CallbackSet.cs" />
<Compile Include="Core\ProtoBuf\Meta\MetaType.cs" />
<Compile Include="Core\ProtoBuf\Meta\RuntimeTypeModel.cs" />
<Compile Include="Core\ProtoBuf\Meta\SubType.cs" />
<Compile Include="Core\ProtoBuf\Meta\TypeFormatEventArgs.cs" />
<Compile Include="Core\ProtoBuf\Meta\TypeModel.cs" />
<Compile Include="Core\ProtoBuf\Meta\ValueMember.cs" />
<Compile Include="Core\ProtoBuf\NetObjectCache.cs" />
<Compile Include="Core\ProtoBuf\PrefixStyle.cs" />
<Compile Include="Core\ProtoBuf\ProtoContractAttribute.cs" />
<Compile Include="Core\ProtoBuf\ProtoEnumAttribute.cs" />
<Compile Include="Core\ProtoBuf\ProtoException.cs" />
<Compile Include="Core\ProtoBuf\ProtoIgnoreAttribute.cs" />
<Compile Include="Core\ProtoBuf\ProtoIncludeAttribute.cs" />
<Compile Include="Core\ProtoBuf\ProtoMemberAttribute.cs" />
<Compile Include="Core\ProtoBuf\ProtoReader.cs" />
<Compile Include="Core\ProtoBuf\ProtoWriter.cs" />
<Compile Include="Core\ProtoBuf\SerializationContext.cs" />
<Compile Include="Core\ProtoBuf\Serializer.cs" />
<Compile Include="Core\ProtoBuf\Serializers\ArrayDecorator.cs" />
<Compile Include="Core\ProtoBuf\Serializers\BlobSerializer.cs" />
<Compile Include="Core\ProtoBuf\Serializers\BooleanSerializer.cs" />
<Compile Include="Core\ProtoBuf\Serializers\ByteSerializer.cs" />
<Compile Include="Core\ProtoBuf\Serializers\CharSerializer.cs" />
<Compile Include="Core\ProtoBuf\Serializers\CompiledSerializer.cs" />
<Compile Include="Core\ProtoBuf\Serializers\DateTimeSerializer.cs" />
<Compile Include="Core\ProtoBuf\Serializers\DecimalSerializer.cs" />
<Compile Include="Core\ProtoBuf\Serializers\DefaultValueDecorator.cs" />
<Compile Include="Core\ProtoBuf\Serializers\DoubleSerializer.cs" />
<Compile Include="Core\ProtoBuf\Serializers\EnumSerializer.cs" />
<Compile Include="Core\ProtoBuf\Serializers\FieldDecorator.cs" />
<Compile Include="Core\ProtoBuf\Serializers\GuidSerializer.cs" />
<Compile Include="Core\ProtoBuf\Serializers\Int16Serializer.cs" />
<Compile Include="Core\ProtoBuf\Serializers\Int32Serializer.cs" />
<Compile Include="Core\ProtoBuf\Serializers\Int64Serializer.cs" />
<Compile Include="Core\ProtoBuf\Serializers\IProtoSerializer.cs" />
<Compile Include="Core\ProtoBuf\Serializers\IProtoTypeSerializer.cs" />
<Compile Include="Core\ProtoBuf\Serializers\ISerializerProxy.cs" />
<Compile Include="Core\ProtoBuf\Serializers\KeyValuePairDecorator.cs" />
<Compile Include="Core\ProtoBuf\Serializers\ListDecorator.cs" />
<Compile Include="Core\ProtoBuf\Serializers\MemberSpecifiedDecorator.cs" />
<Compile Include="Core\ProtoBuf\Serializers\NetObjectSerializer.cs" />
<Compile Include="Core\ProtoBuf\Serializers\NullDecorator.cs" />
<Compile Include="Core\ProtoBuf\Serializers\ParseableSerializer.cs" />
<Compile Include="Core\ProtoBuf\Serializers\PropertyDecorator.cs" />
<Compile Include="Core\ProtoBuf\Serializers\ProtoDecoratorBase.cs" />
<Compile Include="Core\ProtoBuf\Serializers\SByteSerializer.cs" />
<Compile Include="Core\ProtoBuf\Serializers\SingleSerializer.cs" />
<Compile Include="Core\ProtoBuf\Serializers\StringSerializer.cs" />
<Compile Include="Core\ProtoBuf\Serializers\SubItemSerializer.cs" />
<Compile Include="Core\ProtoBuf\Serializers\SurrogateSerializer.cs" />
<Compile Include="Core\ProtoBuf\Serializers\SystemTypeSerializer.cs" />
<Compile Include="Core\ProtoBuf\Serializers\TagDecorator.cs" />
<Compile Include="Core\ProtoBuf\Serializers\TimeSpanSerializer.cs" />
<Compile Include="Core\ProtoBuf\Serializers\TupleSerializer.cs" />
<Compile Include="Core\ProtoBuf\Serializers\TypeSerializer.cs" />
<Compile Include="Core\ProtoBuf\Serializers\UInt16Serializer.cs" />
<Compile Include="Core\ProtoBuf\Serializers\UInt32Serializer.cs" />
<Compile Include="Core\ProtoBuf\Serializers\UInt64Serializer.cs" />
<Compile Include="Core\ProtoBuf\Serializers\UriDecorator.cs" />
<Compile Include="Core\ProtoBuf\ServiceModel\ProtoBehaviorAttribute.cs" />
<Compile Include="Core\ProtoBuf\ServiceModel\ProtoBehaviorExtensionElement.cs" />
<Compile Include="Core\ProtoBuf\ServiceModel\ProtoEndpointBehavior.cs" />
<Compile Include="Core\ProtoBuf\ServiceModel\ProtoOperationBehavior.cs" />
<Compile Include="Core\ProtoBuf\ServiceModel\XmlProtoSerializer.cs" />
<Compile Include="Core\ProtoBuf\SubItemToken.cs" />
<Compile Include="Core\ProtoBuf\WireType.cs" />
<Compile Include="Core\Helper\GeoLocationHelper.cs" />
<Compile Include="Core\Utilities\Keylogger.cs" />
<Compile Include="Enums\MouseAction.cs" />

View File

@ -0,0 +1,110 @@
/*
* Copyright 2015 Tomi Valkeinen
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
using System;
using System.Collections.Generic;
using System.Reflection;
namespace xClient.Core.NetSerializer
{
public sealed class TypeData
{
public TypeData(ushort typeID, IDynamicTypeSerializer serializer)
{
this.TypeID = typeID;
this.TypeSerializer = serializer;
this.NeedsInstanceParameter = true;
}
public TypeData(ushort typeID, MethodInfo writer, MethodInfo reader)
{
this.TypeID = typeID;
this.WriterMethodInfo = writer;
this.ReaderMethodInfo = reader;
this.NeedsInstanceParameter = writer.GetParameters().Length == 3;
}
public readonly ushort TypeID;
public bool IsGenerated { get { return this.TypeSerializer != null; } }
public readonly IDynamicTypeSerializer TypeSerializer;
public MethodInfo WriterMethodInfo;
public MethodInfo ReaderMethodInfo;
public bool NeedsInstanceParameter { get; private set; }
}
public sealed class CodeGenContext
{
readonly Dictionary<Type, TypeData> m_typeMap;
public CodeGenContext(Dictionary<Type, TypeData> typeMap)
{
m_typeMap = typeMap;
var td = m_typeMap[typeof(object)];
this.SerializerSwitchMethodInfo = td.WriterMethodInfo;
this.DeserializerSwitchMethodInfo = td.ReaderMethodInfo;
}
public MethodInfo SerializerSwitchMethodInfo { get; private set; }
public MethodInfo DeserializerSwitchMethodInfo { get; private set; }
public MethodInfo GetWriterMethodInfo(Type type)
{
return m_typeMap[type].WriterMethodInfo;
}
public MethodInfo GetReaderMethodInfo(Type type)
{
return m_typeMap[type].ReaderMethodInfo;
}
public bool IsGenerated(Type type)
{
return m_typeMap[type].IsGenerated;
}
public IDictionary<Type, TypeData> TypeMap { get { return m_typeMap; } }
bool CanCallDirect(Type type)
{
// We can call the (De)serializer method directly for:
// - Value types
// - Array types
// - Sealed types with static (De)serializer method, as the method will handle null
// Other reference types go through the (De)serializerSwitch
bool direct;
if (type.IsValueType || type.IsArray)
direct = true;
else if (type.IsSealed && IsGenerated(type) == false)
direct = true;
else
direct = false;
return direct;
}
public TypeData GetTypeData(Type type)
{
return m_typeMap[type];
}
public TypeData GetTypeDataForCall(Type type)
{
bool direct = CanCallDirect(type);
if (!direct)
type = typeof(object);
return GetTypeData(type);
}
}
}

View File

@ -0,0 +1,89 @@
/*
* Copyright 2015 Tomi Valkeinen
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
namespace xClient.Core.NetSerializer
{
static class Helpers
{
public static readonly ConstructorInfo ExceptionCtorInfo = typeof(Exception).GetConstructor(BindingFlags.Public | BindingFlags.Instance, null, new Type[0], null);
public static IEnumerable<FieldInfo> GetFieldInfos(Type type)
{
Debug.Assert(type.IsSerializable);
var fields = type.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly)
.Where(fi => (fi.Attributes & FieldAttributes.NotSerialized) == 0)
.OrderBy(f => f.Name, StringComparer.Ordinal);
if (type.BaseType == null)
{
return fields;
}
else
{
var baseFields = GetFieldInfos(type.BaseType);
return baseFields.Concat(fields);
}
}
public static DynamicMethod GenerateDynamicSerializerStub(Type type)
{
var dm = new DynamicMethod("Serialize", null,
new Type[] { typeof(Serializer), typeof(Stream), type },
typeof(Serializer), true);
dm.DefineParameter(1, ParameterAttributes.None, "serializer");
dm.DefineParameter(2, ParameterAttributes.None, "stream");
dm.DefineParameter(3, ParameterAttributes.None, "value");
return dm;
}
public static DynamicMethod GenerateDynamicDeserializerStub(Type type)
{
var dm = new DynamicMethod("Deserialize", null,
new Type[] { typeof(Serializer), typeof(Stream), type.MakeByRefType() },
typeof(Serializer), true);
dm.DefineParameter(1, ParameterAttributes.None, "serializer");
dm.DefineParameter(2, ParameterAttributes.None, "stream");
dm.DefineParameter(3, ParameterAttributes.Out, "value");
return dm;
}
#if GENERATE_DEBUGGING_ASSEMBLY
public static MethodBuilder GenerateStaticSerializerStub(TypeBuilder tb, Type type)
{
var mb = tb.DefineMethod("Serialize", MethodAttributes.Public | MethodAttributes.Static, null,
new Type[] { typeof(Serializer), typeof(Stream), type });
mb.DefineParameter(1, ParameterAttributes.None, "serializer");
mb.DefineParameter(2, ParameterAttributes.None, "stream");
mb.DefineParameter(3, ParameterAttributes.None, "value");
return mb;
}
public static MethodBuilder GenerateStaticDeserializerStub(TypeBuilder tb, Type type)
{
var mb = tb.DefineMethod("Deserialize", MethodAttributes.Public | MethodAttributes.Static, null,
new Type[] { typeof(Serializer), typeof(Stream), type.MakeByRefType() });
mb.DefineParameter(1, ParameterAttributes.None, "serializer");
mb.DefineParameter(2, ParameterAttributes.None, "stream");
mb.DefineParameter(3, ParameterAttributes.Out, "value");
return mb;
}
#endif
}
}

View File

@ -0,0 +1,49 @@
/*
* Copyright 2015 Tomi Valkeinen
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Reflection.Emit;
namespace xClient.Core.NetSerializer
{
public interface ITypeSerializer
{
/// <summary>
/// Returns if this TypeSerializer handles the given type
/// </summary>
bool Handles(Type type);
/// <summary>
/// Return types that are needed to serialize the given type
/// </summary>
IEnumerable<Type> GetSubtypes(Type type);
}
public interface IStaticTypeSerializer : ITypeSerializer
{
/// <summary>
/// Get static methods used to serialize and deserialize the given type
/// </summary>
void GetStaticMethods(Type type, out MethodInfo writer, out MethodInfo reader);
}
public interface IDynamicTypeSerializer : ITypeSerializer
{
/// <summary>
/// Generate code to serialize the given type
/// </summary>
void GenerateWriterMethod(Type type, CodeGenContext ctx, ILGenerator il);
/// <summary>
/// Generate code to deserialize the given type
/// </summary>
void GenerateReaderMethod(Type type, CodeGenContext ctx, ILGenerator il);
}
}

View File

@ -0,0 +1,521 @@
/*
* Copyright 2015 Tomi Valkeinen
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
using System;
using System.IO;
using System.Reflection;
using System.Text;
namespace xClient.Core.NetSerializer
{
public static class Primitives
{
public static MethodInfo GetWritePrimitive(Type type)
{
return typeof(Primitives).GetMethod("WritePrimitive",
BindingFlags.Static | BindingFlags.Public | BindingFlags.ExactBinding, null,
new Type[] { typeof(Stream), type }, null);
}
public static MethodInfo GetReaderPrimitive(Type type)
{
return typeof(Primitives).GetMethod("ReadPrimitive",
BindingFlags.Static | BindingFlags.Public | BindingFlags.ExactBinding, null,
new Type[] { typeof(Stream), type.MakeByRefType() }, null);
}
static uint EncodeZigZag32(int n)
{
return (uint)((n << 1) ^ (n >> 31));
}
static ulong EncodeZigZag64(long n)
{
return (ulong)((n << 1) ^ (n >> 63));
}
static int DecodeZigZag32(uint n)
{
return (int)(n >> 1) ^ -(int)(n & 1);
}
static long DecodeZigZag64(ulong n)
{
return (long)(n >> 1) ^ -(long)(n & 1);
}
static uint ReadVarint32(Stream stream)
{
int result = 0;
int offset = 0;
for (; offset < 32; offset += 7)
{
int b = stream.ReadByte();
if (b == -1)
throw new EndOfStreamException();
result |= (b & 0x7f) << offset;
if ((b & 0x80) == 0)
return (uint)result;
}
throw new InvalidDataException();
}
static void WriteVarint32(Stream stream, uint value)
{
for (; value >= 0x80u; value >>= 7)
stream.WriteByte((byte)(value | 0x80u));
stream.WriteByte((byte)value);
}
static ulong ReadVarint64(Stream stream)
{
long result = 0;
int offset = 0;
for (; offset < 64; offset += 7)
{
int b = stream.ReadByte();
if (b == -1)
throw new EndOfStreamException();
result |= ((long)(b & 0x7f)) << offset;
if ((b & 0x80) == 0)
return (ulong)result;
}
throw new InvalidDataException();
}
static void WriteVarint64(Stream stream, ulong value)
{
for (; value >= 0x80u; value >>= 7)
stream.WriteByte((byte)(value | 0x80u));
stream.WriteByte((byte)value);
}
public static void WritePrimitive(Stream stream, bool value)
{
stream.WriteByte(value ? (byte)1 : (byte)0);
}
public static void ReadPrimitive(Stream stream, out bool value)
{
var b = stream.ReadByte();
value = b != 0;
}
public static void WritePrimitive(Stream stream, byte value)
{
stream.WriteByte(value);
}
public static void ReadPrimitive(Stream stream, out byte value)
{
value = (byte)stream.ReadByte();
}
public static void WritePrimitive(Stream stream, sbyte value)
{
stream.WriteByte((byte)value);
}
public static void ReadPrimitive(Stream stream, out sbyte value)
{
value = (sbyte)stream.ReadByte();
}
public static void WritePrimitive(Stream stream, char value)
{
WriteVarint32(stream, value);
}
public static void ReadPrimitive(Stream stream, out char value)
{
value = (char)ReadVarint32(stream);
}
public static void WritePrimitive(Stream stream, ushort value)
{
WriteVarint32(stream, value);
}
public static void ReadPrimitive(Stream stream, out ushort value)
{
value = (ushort)ReadVarint32(stream);
}
public static void WritePrimitive(Stream stream, short value)
{
WriteVarint32(stream, EncodeZigZag32(value));
}
public static void ReadPrimitive(Stream stream, out short value)
{
value = (short)DecodeZigZag32(ReadVarint32(stream));
}
public static void WritePrimitive(Stream stream, uint value)
{
WriteVarint32(stream, value);
}
public static void ReadPrimitive(Stream stream, out uint value)
{
value = ReadVarint32(stream);
}
public static void WritePrimitive(Stream stream, int value)
{
WriteVarint32(stream, EncodeZigZag32(value));
}
public static void ReadPrimitive(Stream stream, out int value)
{
value = DecodeZigZag32(ReadVarint32(stream));
}
public static void WritePrimitive(Stream stream, ulong value)
{
WriteVarint64(stream, value);
}
public static void ReadPrimitive(Stream stream, out ulong value)
{
value = ReadVarint64(stream);
}
public static void WritePrimitive(Stream stream, long value)
{
WriteVarint64(stream, EncodeZigZag64(value));
}
public static void ReadPrimitive(Stream stream, out long value)
{
value = DecodeZigZag64(ReadVarint64(stream));
}
#if !NO_UNSAFE
public static unsafe void WritePrimitive(Stream stream, float value)
{
uint v = *(uint*)(&value);
WriteVarint32(stream, v);
}
public static unsafe void ReadPrimitive(Stream stream, out float value)
{
uint v = ReadVarint32(stream);
value = *(float*)(&v);
}
public static unsafe void WritePrimitive(Stream stream, double value)
{
ulong v = *(ulong*)(&value);
WriteVarint64(stream, v);
}
public static unsafe void ReadPrimitive(Stream stream, out double value)
{
ulong v = ReadVarint64(stream);
value = *(double*)(&v);
}
#else
public static void WritePrimitive(Stream stream, float value)
{
WritePrimitive(stream, (double)value);
}
public static void ReadPrimitive(Stream stream, out float value)
{
double v;
ReadPrimitive(stream, out v);
value = (float)v;
}
public static void WritePrimitive(Stream stream, double value)
{
ulong v = (ulong)BitConverter.DoubleToInt64Bits(value);
WriteVarint64(stream, v);
}
public static void ReadPrimitive(Stream stream, out double value)
{
ulong v = ReadVarint64(stream);
value = BitConverter.Int64BitsToDouble((long)v);
}
#endif
public static void WritePrimitive(Stream stream, DateTime value)
{
long v = value.ToBinary();
WritePrimitive(stream, v);
}
public static void ReadPrimitive(Stream stream, out DateTime value)
{
long v;
ReadPrimitive(stream, out v);
value = DateTime.FromBinary(v);
}
#if NO_UNSAFE
public static void WritePrimitive(Stream stream, string value)
{
if (value == null)
{
WritePrimitive(stream, (uint)0);
return;
}
var encoding = new UTF8Encoding(false, true);
int len = encoding.GetByteCount(value);
WritePrimitive(stream, (uint)len + 1);
var buf = new byte[len];
encoding.GetBytes(value, 0, value.Length, buf, 0);
stream.Write(buf, 0, len);
}
public static void ReadPrimitive(Stream stream, out string value)
{
uint len;
ReadPrimitive(stream, out len);
if (len == 0)
{
value = null;
return;
}
else if (len == 1)
{
value = string.Empty;
return;
}
len -= 1;
var encoding = new UTF8Encoding(false, true);
var buf = new byte[len];
int l = 0;
while (l < len)
{
int r = stream.Read(buf, l, (int)len - l);
if (r == 0)
throw new EndOfStreamException();
l += r;
}
value = encoding.GetString(buf);
}
#else
sealed class StringHelper
{
public StringHelper()
{
this.Encoding = new UTF8Encoding(false, true);
}
public const int BYTEBUFFERLEN = 256;
public const int CHARBUFFERLEN = 128;
Encoder m_encoder;
Decoder m_decoder;
byte[] m_byteBuffer;
char[] m_charBuffer;
public UTF8Encoding Encoding { get; private set; }
public Encoder Encoder { get { if (m_encoder == null) m_encoder = this.Encoding.GetEncoder(); return m_encoder; } }
public Decoder Decoder { get { if (m_decoder == null) m_decoder = this.Encoding.GetDecoder(); return m_decoder; } }
public byte[] ByteBuffer { get { if (m_byteBuffer == null) m_byteBuffer = new byte[BYTEBUFFERLEN]; return m_byteBuffer; } }
public char[] CharBuffer { get { if (m_charBuffer == null) m_charBuffer = new char[CHARBUFFERLEN]; return m_charBuffer; } }
}
[ThreadStatic]
static StringHelper s_stringHelper;
public unsafe static void WritePrimitive(Stream stream, string value)
{
if (value == null)
{
WritePrimitive(stream, (uint)0);
return;
}
else if (value.Length == 0)
{
WritePrimitive(stream, (uint)1);
return;
}
var helper = s_stringHelper;
if (helper == null)
s_stringHelper = helper = new StringHelper();
var encoder = helper.Encoder;
var buf = helper.ByteBuffer;
int totalChars = value.Length;
int totalBytes;
fixed (char* ptr = value)
totalBytes = encoder.GetByteCount(ptr, totalChars, true);
WritePrimitive(stream, (uint)totalBytes + 1);
WritePrimitive(stream, (uint)totalChars);
int p = 0;
bool completed = false;
while (completed == false)
{
int charsConverted;
int bytesConverted;
fixed (char* src = value)
fixed (byte* dst = buf)
{
encoder.Convert(src + p, totalChars - p, dst, buf.Length, true,
out charsConverted, out bytesConverted, out completed);
}
stream.Write(buf, 0, bytesConverted);
p += charsConverted;
}
}
public static void ReadPrimitive(Stream stream, out string value)
{
uint totalBytes;
ReadPrimitive(stream, out totalBytes);
if (totalBytes == 0)
{
value = null;
return;
}
else if (totalBytes == 1)
{
value = string.Empty;
return;
}
totalBytes -= 1;
uint totalChars;
ReadPrimitive(stream, out totalChars);
var helper = s_stringHelper;
if (helper == null)
s_stringHelper = helper = new StringHelper();
var decoder = helper.Decoder;
var buf = helper.ByteBuffer;
char[] chars;
if (totalChars <= StringHelper.CHARBUFFERLEN)
chars = helper.CharBuffer;
else
chars = new char[totalChars];
int streamBytesLeft = (int)totalBytes;
int cp = 0;
while (streamBytesLeft > 0)
{
int bytesInBuffer = stream.Read(buf, 0, Math.Min(buf.Length, streamBytesLeft));
if (bytesInBuffer == 0)
throw new EndOfStreamException();
streamBytesLeft -= bytesInBuffer;
bool flush = streamBytesLeft == 0 ? true : false;
bool completed = false;
int p = 0;
while (completed == false)
{
int charsConverted;
int bytesConverted;
decoder.Convert(buf, p, bytesInBuffer - p,
chars, cp, (int)totalChars - cp,
flush,
out bytesConverted, out charsConverted, out completed);
p += bytesConverted;
cp += charsConverted;
}
}
value = new string(chars, 0, (int)totalChars);
}
#endif
public static void WritePrimitive(Stream stream, byte[] value)
{
if (value == null)
{
WritePrimitive(stream, (uint)0);
return;
}
WritePrimitive(stream, (uint)value.Length + 1);
stream.Write(value, 0, value.Length);
}
static readonly byte[] s_emptyByteArray = new byte[0];
public static void ReadPrimitive(Stream stream, out byte[] value)
{
uint len;
ReadPrimitive(stream, out len);
if (len == 0)
{
value = null;
return;
}
else if (len == 1)
{
value = s_emptyByteArray;
return;
}
len -= 1;
value = new byte[len];
int l = 0;
while (l < len)
{
int r = stream.Read(value, l, (int)len - l);
if (r == 0)
throw new EndOfStreamException();
l += r;
}
}
}
}

View File

@ -0,0 +1,254 @@
/*
* Copyright 2015 Tomi Valkeinen
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using xClient.Core.NetSerializer.TypeSerializers;
namespace xClient.Core.NetSerializer
{
public class Serializer
{
Dictionary<Type, ushort> m_typeIDMap;
delegate void SerializerSwitch(Serializer serializer, Stream stream, object ob);
delegate void DeserializerSwitch(Serializer serializer, Stream stream, out object ob);
SerializerSwitch m_serializerSwitch;
DeserializerSwitch m_deserializerSwitch;
static ITypeSerializer[] s_typeSerializers = new ITypeSerializer[] {
new ObjectSerializer(),
new PrimitivesSerializer(),
new ArraySerializer(),
new EnumSerializer(),
new DictionarySerializer(),
new GenericSerializer(),
};
ITypeSerializer[] m_userTypeSerializers;
/// <summary>
/// Initialize NetSerializer
/// </summary>
/// <param name="rootTypes">Types to be (de)serialized</param>
public Serializer(IEnumerable<Type> rootTypes)
: this(rootTypes, new ITypeSerializer[0])
{
}
/// <summary>
/// Initialize NetSerializer
/// </summary>
/// <param name="rootTypes">Types to be (de)serialized</param>
/// <param name="userTypeSerializers">Array of custom serializers</param>
public Serializer(IEnumerable<Type> rootTypes, ITypeSerializer[] userTypeSerializers)
{
if (userTypeSerializers.All(s => s is IDynamicTypeSerializer || s is IStaticTypeSerializer) == false)
throw new ArgumentException("TypeSerializers have to implement IDynamicTypeSerializer or IStaticTypeSerializer");
m_userTypeSerializers = userTypeSerializers;
var typeDataMap = GenerateTypeData(rootTypes);
GenerateDynamic(typeDataMap);
m_typeIDMap = typeDataMap.ToDictionary(kvp => kvp.Key, kvp => kvp.Value.TypeID);
#if GENERATE_DEBUGGING_ASSEMBLY
// Note: GenerateDebugAssembly overwrites some fields from typeDataMap
GenerateDebugAssembly(typeDataMap);
#endif
}
public void Serialize(Stream stream, object data)
{
m_serializerSwitch(this, stream, data);
}
public object Deserialize(Stream stream)
{
object o;
m_deserializerSwitch(this, stream, out o);
return o;
}
Dictionary<Type, TypeData> GenerateTypeData(IEnumerable<Type> rootTypes)
{
var map = new Dictionary<Type, TypeData>();
var stack = new Stack<Type>(PrimitivesSerializer.GetSupportedTypes().Concat(rootTypes));
stack.Push(typeof(object));
// TypeID 0 is reserved for null
ushort typeID = 1;
while (stack.Count > 0)
{
var type = stack.Pop();
if (map.ContainsKey(type))
continue;
if (type.IsAbstract || type.IsInterface)
continue;
if (type.ContainsGenericParameters)
throw new NotSupportedException(String.Format("Type {0} contains generic parameters", type.FullName));
var serializer = m_userTypeSerializers.FirstOrDefault(h => h.Handles(type));
if (serializer == null)
serializer = s_typeSerializers.FirstOrDefault(h => h.Handles(type));
if (serializer == null)
throw new NotSupportedException(String.Format("No serializer for {0}", type.FullName));
foreach (var t in serializer.GetSubtypes(type))
stack.Push(t);
TypeData typeData;
if (serializer is IStaticTypeSerializer)
{
var sts = (IStaticTypeSerializer)serializer;
MethodInfo writer;
MethodInfo reader;
sts.GetStaticMethods(type, out writer, out reader);
Debug.Assert(writer != null && reader != null);
typeData = new TypeData(typeID++, writer, reader);
}
else if (serializer is IDynamicTypeSerializer)
{
var dts = (IDynamicTypeSerializer)serializer;
typeData = new TypeData(typeID++, dts);
}
else
{
throw new Exception();
}
map[type] = typeData;
}
return map;
}
void GenerateDynamic(Dictionary<Type, TypeData> map)
{
/* generate stubs */
foreach (var kvp in map)
{
var type = kvp.Key;
var td = kvp.Value;
if (!td.IsGenerated)
continue;
td.WriterMethodInfo = Helpers.GenerateDynamicSerializerStub(type);
td.ReaderMethodInfo = Helpers.GenerateDynamicDeserializerStub(type);
}
var ctx = new CodeGenContext(map);
/* generate bodies */
foreach (var kvp in map)
{
var type = kvp.Key;
var td = kvp.Value;
if (!td.IsGenerated)
continue;
var writerDm = (DynamicMethod)td.WriterMethodInfo;
td.TypeSerializer.GenerateWriterMethod(type, ctx, writerDm.GetILGenerator());
var readerDm = (DynamicMethod)td.ReaderMethodInfo;
td.TypeSerializer.GenerateReaderMethod(type, ctx, readerDm.GetILGenerator());
}
var writer = (DynamicMethod)ctx.GetWriterMethodInfo(typeof(object));
var reader = (DynamicMethod)ctx.GetReaderMethodInfo(typeof(object));
m_serializerSwitch = (SerializerSwitch)writer.CreateDelegate(typeof(SerializerSwitch));
m_deserializerSwitch = (DeserializerSwitch)reader.CreateDelegate(typeof(DeserializerSwitch));
}
#if GENERATE_DEBUGGING_ASSEMBLY
static void GenerateDebugAssembly(Dictionary<Type, TypeData> map)
{
var ab = AppDomain.CurrentDomain.DefineDynamicAssembly(new AssemblyName("NetSerializerDebug"), AssemblyBuilderAccess.RunAndSave);
var modb = ab.DefineDynamicModule("NetSerializerDebug.dll");
var tb = modb.DefineType("NetSerializer", TypeAttributes.Public);
/* generate stubs */
foreach (var kvp in map)
{
var type = kvp.Key;
var td = kvp.Value;
if (!td.IsGenerated)
continue;
td.WriterMethodInfo = Helpers.GenerateStaticSerializerStub(tb, type);
td.ReaderMethodInfo = Helpers.GenerateStaticDeserializerStub(tb, type);
}
var ctx = new CodeGenContext(map);
/* generate bodies */
foreach (var kvp in map)
{
var type = kvp.Key;
var td = kvp.Value;
if (!td.IsGenerated)
continue;
var writerMb = (MethodBuilder)td.WriterMethodInfo;
td.TypeSerializer.GenerateWriterMethod(type, ctx, writerMb.GetILGenerator());
var readerMb = (MethodBuilder)td.ReaderMethodInfo;
td.TypeSerializer.GenerateReaderMethod(type, ctx, readerMb.GetILGenerator());
}
tb.CreateType();
ab.Save("NetSerializerDebug.dll");
}
#endif
/* called from the dynamically generated code */
ushort GetTypeID(object ob)
{
ushort id;
if (ob == null)
return 0;
var type = ob.GetType();
if (m_typeIDMap.TryGetValue(type, out id) == false)
throw new InvalidOperationException(String.Format("Unknown type {0}", type.FullName));
return id;
}
}
}

View File

@ -0,0 +1,193 @@
/*
* Copyright 2015 Tomi Valkeinen
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
using System;
using System.Collections.Generic;
using System.Reflection.Emit;
namespace xClient.Core.NetSerializer.TypeSerializers
{
class ArraySerializer : IDynamicTypeSerializer
{
public bool Handles(Type type)
{
if (!type.IsArray)
return false;
if (type.GetArrayRank() != 1)
throw new NotSupportedException(String.Format("Multi-dim arrays not supported: {0}", type.FullName));
return true;
}
public IEnumerable<Type> GetSubtypes(Type type)
{
yield return type.GetElementType();
}
public void GenerateWriterMethod(Type type, CodeGenContext ctx, ILGenerator il)
{
var elemType = type.GetElementType();
var notNullLabel = il.DefineLabel();
il.Emit(OpCodes.Ldarg_2);
il.Emit(OpCodes.Brtrue_S, notNullLabel);
// if value == null, write 0
il.Emit(OpCodes.Ldarg_1);
il.Emit(OpCodes.Ldc_I4_0);
il.Emit(OpCodes.Tailcall);
il.Emit(OpCodes.Call, ctx.GetWriterMethodInfo(typeof(uint)));
il.Emit(OpCodes.Ret);
il.MarkLabel(notNullLabel);
// write array len + 1
il.Emit(OpCodes.Ldarg_1);
il.Emit(OpCodes.Ldarg_2);
il.Emit(OpCodes.Ldlen);
il.Emit(OpCodes.Ldc_I4_1);
il.Emit(OpCodes.Add);
il.Emit(OpCodes.Call, ctx.GetWriterMethodInfo(typeof(uint)));
// declare i
var idxLocal = il.DeclareLocal(typeof(int));
// i = 0
il.Emit(OpCodes.Ldc_I4_0);
il.Emit(OpCodes.Stloc_S, idxLocal);
var loopBodyLabel = il.DefineLabel();
var loopCheckLabel = il.DefineLabel();
il.Emit(OpCodes.Br_S, loopCheckLabel);
// loop body
il.MarkLabel(loopBodyLabel);
var data = ctx.GetTypeDataForCall(elemType);
if (data.NeedsInstanceParameter)
il.Emit(OpCodes.Ldarg_0);
// write element at index i
il.Emit(OpCodes.Ldarg_1);
il.Emit(OpCodes.Ldarg_2);
il.Emit(OpCodes.Ldloc_S, idxLocal);
il.Emit(OpCodes.Ldelem, elemType);
il.Emit(OpCodes.Call, data.WriterMethodInfo);
// i = i + 1
il.Emit(OpCodes.Ldloc_S, idxLocal);
il.Emit(OpCodes.Ldc_I4_1);
il.Emit(OpCodes.Add);
il.Emit(OpCodes.Stloc_S, idxLocal);
il.MarkLabel(loopCheckLabel);
// loop condition
il.Emit(OpCodes.Ldloc_S, idxLocal);
il.Emit(OpCodes.Ldarg_2);
il.Emit(OpCodes.Ldlen);
il.Emit(OpCodes.Conv_I4);
il.Emit(OpCodes.Clt);
il.Emit(OpCodes.Brtrue_S, loopBodyLabel);
il.Emit(OpCodes.Ret);
}
public void GenerateReaderMethod(Type type, CodeGenContext ctx, ILGenerator il)
{
var elemType = type.GetElementType();
var lenLocal = il.DeclareLocal(typeof(uint));
// read array len
il.Emit(OpCodes.Ldarg_1);
il.Emit(OpCodes.Ldloca_S, lenLocal);
il.Emit(OpCodes.Call, ctx.GetReaderMethodInfo(typeof(uint)));
var notNullLabel = il.DefineLabel();
/* if len == 0, return null */
il.Emit(OpCodes.Ldloc_S, lenLocal);
il.Emit(OpCodes.Brtrue_S, notNullLabel);
il.Emit(OpCodes.Ldarg_2);
il.Emit(OpCodes.Ldnull);
il.Emit(OpCodes.Stind_Ref);
il.Emit(OpCodes.Ret);
il.MarkLabel(notNullLabel);
var arrLocal = il.DeclareLocal(type);
// create new array with len - 1
il.Emit(OpCodes.Ldloc_S, lenLocal);
il.Emit(OpCodes.Ldc_I4_1);
il.Emit(OpCodes.Sub);
il.Emit(OpCodes.Newarr, elemType);
il.Emit(OpCodes.Stloc_S, arrLocal);
// declare i
var idxLocal = il.DeclareLocal(typeof(int));
// i = 0
il.Emit(OpCodes.Ldc_I4_0);
il.Emit(OpCodes.Stloc_S, idxLocal);
var loopBodyLabel = il.DefineLabel();
var loopCheckLabel = il.DefineLabel();
il.Emit(OpCodes.Br_S, loopCheckLabel);
// loop body
il.MarkLabel(loopBodyLabel);
// read element to arr[i]
var data = ctx.GetTypeDataForCall(elemType);
if (data.NeedsInstanceParameter)
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Ldarg_1);
il.Emit(OpCodes.Ldloc_S, arrLocal);
il.Emit(OpCodes.Ldloc_S, idxLocal);
il.Emit(OpCodes.Ldelema, elemType);
il.Emit(OpCodes.Call, data.ReaderMethodInfo);
// i = i + 1
il.Emit(OpCodes.Ldloc_S, idxLocal);
il.Emit(OpCodes.Ldc_I4_1);
il.Emit(OpCodes.Add);
il.Emit(OpCodes.Stloc_S, idxLocal);
il.MarkLabel(loopCheckLabel);
// loop condition
il.Emit(OpCodes.Ldloc_S, idxLocal);
il.Emit(OpCodes.Ldloc_S, arrLocal);
il.Emit(OpCodes.Ldlen);
il.Emit(OpCodes.Conv_I4);
il.Emit(OpCodes.Clt);
il.Emit(OpCodes.Brtrue_S, loopBodyLabel);
// store new array to the out value
il.Emit(OpCodes.Ldarg_2);
il.Emit(OpCodes.Ldloc_S, arrLocal);
il.Emit(OpCodes.Stind_Ref);
il.Emit(OpCodes.Ret);
}
}
}

View File

@ -0,0 +1,147 @@
/*
* Copyright 2015 Tomi Valkeinen
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
namespace xClient.Core.NetSerializer.TypeSerializers
{
public class DictionarySerializer : IStaticTypeSerializer
{
public bool Handles(Type type)
{
if (!type.IsGenericType)
return false;
var genTypeDef = type.GetGenericTypeDefinition();
return genTypeDef == typeof(Dictionary<,>);
}
public IEnumerable<Type> GetSubtypes(Type type)
{
// Dictionary<K,V> is stored as KeyValuePair<K,V>[]
var genArgs = type.GetGenericArguments();
var serializedType = typeof(KeyValuePair<,>).MakeGenericType(genArgs).MakeArrayType();
yield return serializedType;
}
public void GetStaticMethods(Type type, out MethodInfo writer, out MethodInfo reader)
{
Debug.Assert(type.IsGenericType);
if (!type.IsGenericType)
throw new Exception();
var genTypeDef = type.GetGenericTypeDefinition();
Debug.Assert(genTypeDef == typeof(Dictionary<,>));
var containerType = this.GetType();
writer = GetGenWriter(containerType, genTypeDef);
reader = GetGenReader(containerType, genTypeDef);
var genArgs = type.GetGenericArguments();
writer = writer.MakeGenericMethod(genArgs);
reader = reader.MakeGenericMethod(genArgs);
}
static MethodInfo GetGenWriter(Type containerType, Type genType)
{
var mis = containerType.GetMethods(BindingFlags.Static | BindingFlags.Public)
.Where(mi => mi.IsGenericMethod && mi.Name == "WritePrimitive");
foreach (var mi in mis)
{
var p = mi.GetParameters();
if (p.Length != 3)
continue;
if (p[1].ParameterType != typeof(Stream))
continue;
var paramType = p[2].ParameterType;
if (paramType.IsGenericType == false)
continue;
var genParamType = paramType.GetGenericTypeDefinition();
if (genType == genParamType)
return mi;
}
return null;
}
static MethodInfo GetGenReader(Type containerType, Type genType)
{
var mis = containerType.GetMethods(BindingFlags.Static | BindingFlags.Public)
.Where(mi => mi.IsGenericMethod && mi.Name == "ReadPrimitive");
foreach (var mi in mis)
{
var p = mi.GetParameters();
if (p.Length != 3)
continue;
if (p[1].ParameterType != typeof(Stream))
continue;
var paramType = p[2].ParameterType;
if (paramType.IsByRef == false)
continue;
paramType = paramType.GetElementType();
if (paramType.IsGenericType == false)
continue;
var genParamType = paramType.GetGenericTypeDefinition();
if (genType == genParamType)
return mi;
}
return null;
}
public static void WritePrimitive<TKey, TValue>(Serializer serializer, Stream stream, Dictionary<TKey, TValue> value)
{
var kvpArray = new KeyValuePair<TKey, TValue>[value.Count];
int i = 0;
foreach (var kvp in value)
kvpArray[i++] = kvp;
serializer.Serialize(stream, kvpArray);
}
public static void ReadPrimitive<TKey, TValue>(Serializer serializer, Stream stream, out Dictionary<TKey, TValue> value)
{
var kvpArray = (KeyValuePair<TKey, TValue>[])serializer.Deserialize(stream);
value = new Dictionary<TKey, TValue>(kvpArray.Length);
foreach (var kvp in kvpArray)
value.Add(kvp.Key, kvp.Value);
}
}
}

View File

@ -0,0 +1,40 @@
/*
* Copyright 2015 Tomi Valkeinen
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
namespace xClient.Core.NetSerializer.TypeSerializers
{
public class EnumSerializer : IStaticTypeSerializer
{
public bool Handles(Type type)
{
return type.IsEnum;
}
public IEnumerable<Type> GetSubtypes(Type type)
{
var underlyingType = Enum.GetUnderlyingType(type);
yield return underlyingType;
}
public void GetStaticMethods(Type type, out MethodInfo writer, out MethodInfo reader)
{
Debug.Assert(type.IsEnum);
var underlyingType = Enum.GetUnderlyingType(type);
writer = Primitives.GetWritePrimitive(underlyingType);
reader = Primitives.GetReaderPrimitive(underlyingType);
}
}
}

View File

@ -0,0 +1,121 @@
/*
* Copyright 2015 Tomi Valkeinen
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Reflection.Emit;
namespace xClient.Core.NetSerializer.TypeSerializers
{
public class GenericSerializer : IDynamicTypeSerializer
{
public bool Handles(Type type)
{
if (!type.IsSerializable)
throw new NotSupportedException(String.Format("Type {0} is not marked as Serializable", type.FullName));
if (typeof(System.Runtime.Serialization.ISerializable).IsAssignableFrom(type))
throw new NotSupportedException(String.Format("Cannot serialize {0}: ISerializable not supported", type.FullName));
return true;
}
public IEnumerable<Type> GetSubtypes(Type type)
{
var fields = Helpers.GetFieldInfos(type);
foreach (var field in fields)
yield return field.FieldType;
}
public void GenerateWriterMethod(Type type, CodeGenContext ctx, ILGenerator il)
{
// arg0: Serializer, arg1: Stream, arg2: value
var fields = Helpers.GetFieldInfos(type);
foreach (var field in fields)
{
// Note: the user defined value type is not passed as reference. could cause perf problems with big structs
var fieldType = field.FieldType;
var data = ctx.GetTypeDataForCall(fieldType);
if (data.NeedsInstanceParameter)
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Ldarg_1);
if (type.IsValueType)
il.Emit(OpCodes.Ldarga_S, 2);
else
il.Emit(OpCodes.Ldarg_2);
il.Emit(OpCodes.Ldfld, field);
il.Emit(OpCodes.Call, data.WriterMethodInfo);
}
il.Emit(OpCodes.Ret);
}
public void GenerateReaderMethod(Type type, CodeGenContext ctx, ILGenerator il)
{
// arg0: Serializer, arg1: stream, arg2: out value
if (type.IsClass)
{
// instantiate empty class
il.Emit(OpCodes.Ldarg_2);
var gtfh = typeof(Type).GetMethod("GetTypeFromHandle", BindingFlags.Public | BindingFlags.Static);
var guo = typeof(System.Runtime.Serialization.FormatterServices).GetMethod("GetUninitializedObject", BindingFlags.Public | BindingFlags.Static);
il.Emit(OpCodes.Ldtoken, type);
il.Emit(OpCodes.Call, gtfh);
il.Emit(OpCodes.Call, guo);
il.Emit(OpCodes.Castclass, type);
il.Emit(OpCodes.Stind_Ref);
}
var fields = Helpers.GetFieldInfos(type);
foreach (var field in fields)
{
var fieldType = field.FieldType;
var data = ctx.GetTypeDataForCall(fieldType);
if (data.NeedsInstanceParameter)
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Ldarg_1);
il.Emit(OpCodes.Ldarg_2);
if (type.IsClass)
il.Emit(OpCodes.Ldind_Ref);
il.Emit(OpCodes.Ldflda, field);
il.Emit(OpCodes.Call, data.ReaderMethodInfo);
}
if (typeof(System.Runtime.Serialization.IDeserializationCallback).IsAssignableFrom(type))
{
var miOnDeserialization = typeof(System.Runtime.Serialization.IDeserializationCallback).GetMethod("OnDeserialization",
BindingFlags.Instance | BindingFlags.Public,
null, new[] { typeof(Object) }, null);
il.Emit(OpCodes.Ldarg_2);
il.Emit(OpCodes.Ldnull);
il.Emit(OpCodes.Constrained, type);
il.Emit(OpCodes.Callvirt, miOnDeserialization);
}
il.Emit(OpCodes.Ret);
}
}
}

View File

@ -0,0 +1,157 @@
/*
* Copyright 2015 Tomi Valkeinen
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Reflection.Emit;
namespace xClient.Core.NetSerializer.TypeSerializers
{
class ObjectSerializer : IDynamicTypeSerializer
{
public bool Handles(Type type)
{
return type == typeof(object);
}
public IEnumerable<Type> GetSubtypes(Type type)
{
return new Type[0];
}
public void GenerateWriterMethod(Type obtype, CodeGenContext ctx, ILGenerator il)
{
var getTypeIDMethodInfo = typeof(Serializer).GetMethod("GetTypeID", BindingFlags.NonPublic | BindingFlags.Instance, null,
new Type[] { typeof(object) }, null);
var map = ctx.TypeMap;
// arg0: Serializer, arg1: Stream, arg2: object
var idLocal = il.DeclareLocal(typeof(ushort));
// get TypeID from object's Type
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Ldarg_2);
il.Emit(OpCodes.Call, getTypeIDMethodInfo);
il.Emit(OpCodes.Stloc_S, idLocal);
// write typeID
il.Emit(OpCodes.Ldarg_1);
il.Emit(OpCodes.Ldloc_S, idLocal);
il.Emit(OpCodes.Call, ctx.GetWriterMethodInfo(typeof(ushort)));
// +1 for 0 (null)
var jumpTable = new Label[map.Count + 1];
jumpTable[0] = il.DefineLabel();
foreach (var kvp in map)
jumpTable[kvp.Value.TypeID] = il.DefineLabel();
il.Emit(OpCodes.Ldloc_S, idLocal);
il.Emit(OpCodes.Switch, jumpTable);
il.Emit(OpCodes.Newobj, Helpers.ExceptionCtorInfo);
il.Emit(OpCodes.Throw);
/* null case */
il.MarkLabel(jumpTable[0]);
il.Emit(OpCodes.Ret);
/* cases for types */
foreach (var kvp in map)
{
var type = kvp.Key;
var data = kvp.Value;
il.MarkLabel(jumpTable[data.TypeID]);
if (data.NeedsInstanceParameter)
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Ldarg_1);
il.Emit(OpCodes.Ldarg_2);
il.Emit(type.IsValueType ? OpCodes.Unbox_Any : OpCodes.Castclass, type);
il.Emit(OpCodes.Tailcall);
il.Emit(OpCodes.Call, data.WriterMethodInfo);
il.Emit(OpCodes.Ret);
}
}
public void GenerateReaderMethod(Type obtype, CodeGenContext ctx, ILGenerator il)
{
var map = ctx.TypeMap;
// arg0: Serializer, arg1: stream, arg2: out object
var idLocal = il.DeclareLocal(typeof(ushort));
// read typeID
il.Emit(OpCodes.Ldarg_1);
il.Emit(OpCodes.Ldloca_S, idLocal);
il.Emit(OpCodes.Call, ctx.GetReaderMethodInfo(typeof(ushort)));
// +1 for 0 (null)
var jumpTable = new Label[map.Count + 1];
jumpTable[0] = il.DefineLabel();
foreach (var kvp in map)
jumpTable[kvp.Value.TypeID] = il.DefineLabel();
il.Emit(OpCodes.Ldloc_S, idLocal);
il.Emit(OpCodes.Switch, jumpTable);
il.Emit(OpCodes.Newobj, Helpers.ExceptionCtorInfo);
il.Emit(OpCodes.Throw);
/* null case */
il.MarkLabel(jumpTable[0]);
il.Emit(OpCodes.Ldarg_2);
il.Emit(OpCodes.Ldnull);
il.Emit(OpCodes.Stind_Ref);
il.Emit(OpCodes.Ret);
/* cases for types */
foreach (var kvp in map)
{
var type = kvp.Key;
var data = kvp.Value;
il.MarkLabel(jumpTable[data.TypeID]);
var local = il.DeclareLocal(type);
// call deserializer for this typeID
if (data.NeedsInstanceParameter)
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Ldarg_1);
if (local.LocalIndex < 256)
il.Emit(OpCodes.Ldloca_S, local);
else
il.Emit(OpCodes.Ldloca, local);
il.Emit(OpCodes.Call, data.ReaderMethodInfo);
// write result object to out object
il.Emit(OpCodes.Ldarg_2);
if (local.LocalIndex < 256)
il.Emit(OpCodes.Ldloc_S, local);
else
il.Emit(OpCodes.Ldloc, local);
if (type.IsValueType)
il.Emit(OpCodes.Box, type);
il.Emit(OpCodes.Stind_Ref);
il.Emit(OpCodes.Ret);
}
}
}
}

View File

@ -0,0 +1,52 @@
/*
* Copyright 2015 Tomi Valkeinen
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
namespace xClient.Core.NetSerializer.TypeSerializers
{
public class PrimitivesSerializer : IStaticTypeSerializer
{
static Type[] s_primitives = new Type[] {
typeof(bool),
typeof(byte), typeof(sbyte),
typeof(char),
typeof(ushort), typeof(short),
typeof(uint), typeof(int),
typeof(ulong), typeof(long),
typeof(float), typeof(double),
typeof(string),
typeof(DateTime),
typeof(byte[]),
};
public bool Handles(Type type)
{
return s_primitives.Contains(type);
}
public IEnumerable<Type> GetSubtypes(Type type)
{
yield break;
}
public void GetStaticMethods(Type type, out MethodInfo writer, out MethodInfo reader)
{
writer = Primitives.GetWritePrimitive(type);
reader = Primitives.GetReaderPrimitive(type);
}
public static IEnumerable<Type> GetSupportedTypes()
{
return s_primitives;
}
}
}

View File

@ -4,11 +4,10 @@
using System.Linq;
using System.Net.Sockets;
using System.Threading;
using ProtoBuf;
using ProtoBuf.Meta;
using xClient.Core.Compression;
using xClient.Core.Encryption;
using xClient.Core.Extensions;
using xClient.Core.NetSerializer;
using xClient.Core.Packets;
using xClient.Core.ReverseProxy;
using xClient.Core.ReverseProxy.Packets;
@ -256,6 +255,11 @@ public ReverseProxyClient[] ProxyClients
/// </summary>
public bool Connected { get; private set; }
/// <summary>
/// The packet serializer.
/// </summary>
private Serializer _serializer;
private const bool encryptionEnabled = true;
private const bool compressionEnabled = true;
@ -270,6 +274,8 @@ public Client()
/// <param name="port">The port of the host.</param>
public void Connect(string host, ushort port)
{
if (_serializer == null) throw new Exception("Serializer not initialized");
try
{
Disconnect();
@ -297,7 +303,6 @@ public void Connect(string host, ushort port)
private void Initialize()
{
AddTypeToSerializer(typeof (IPacket), typeof (UnknownPacket));
lock (_proxyClientsLock)
{
_proxyClients = new List<ReverseProxyClient>();
@ -496,9 +501,7 @@ private void AsyncReceive(object state)
using (MemoryStream deserialized = new MemoryStream(_payloadBuffer))
{
IPacket packet =
Serializer.DeserializeWithLengthPrefix<IPacket>(deserialized,
PrefixStyle.Fixed32);
IPacket packet = (IPacket)_serializer.Deserialize(deserialized);
OnClientRead(packet);
}
@ -541,7 +544,7 @@ private void AsyncReceive(object state)
{
using (MemoryStream ms = new MemoryStream())
{
Serializer.SerializeWithLengthPrefix<T>(ms, packet, PrefixStyle.Fixed32);
_serializer.Serialize(ms, packet);
byte[] payload = ms.ToArray();
@ -677,31 +680,13 @@ public void Disconnect()
}
}
/// <summary>
/// Adds a Type to the serializer so a message can be properly serialized.
/// </summary>
/// <param name="parent">The parent type.</param>
/// <param name="type">Type to be added.</param>
public void AddTypeToSerializer(Type parent, Type type)
{
if (type == null || parent == null)
throw new ArgumentNullException();
bool isAlreadyAdded = RuntimeTypeModel.Default[parent].GetSubtypes().Any(subType => subType.DerivedType.Type == type);
if (!isAlreadyAdded)
RuntimeTypeModel.Default[parent].AddSubType(_typeIndex += 1, type);
}
/// <summary>
/// Adds Types to the serializer.
/// </summary>
/// <param name="parent">The parent type, i.e.: IPacket</param>
/// <param name="types">Types to add.</param>
public void AddTypesToSerializer(Type parent, params Type[] types)
public void AddTypesToSerializer(Type[] types)
{
foreach (Type type in types)
AddTypeToSerializer(parent, type);
_serializer = new Serializer(types);
}
public void ConnectReverseProxy(ReverseProxyConnect command)

View File

@ -1,27 +1,21 @@
using ProtoBuf;
using System;
using xClient.Core.Networking;
namespace xClient.Core.Packets.ClientPackets
{
[ProtoContract]
[Serializable]
public class DoDownloadFileResponse : IPacket
{
[ProtoMember(1)]
public int ID { get; set; }
[ProtoMember(2)]
public string Filename { get; set; }
[ProtoMember(3)]
public byte[] Block { get; set; }
[ProtoMember(4)]
public int MaxBlocks { get; set; }
[ProtoMember(5)]
public int CurrentBlock { get; set; }
[ProtoMember(6)]
public string CustomMessage { get; set; }
public DoDownloadFileResponse()
@ -41,8 +35,6 @@ public DoDownloadFileResponse()
public void Execute(Client client)
{
// block thread till send queue is empty to prevent
// allocation of all blocks at once
client.SendBlocking(this);
}
}

View File

@ -1,15 +1,13 @@
using ProtoBuf;
using System;
using xClient.Core.Networking;
namespace xClient.Core.Packets.ClientPackets
{
[ProtoContract]
[Serializable]
public class DoShellExecuteResponse : IPacket
{
[ProtoMember(1)]
public string Output { get; set; }
[ProtoMember(2)]
public bool IsError { get; private set; }
public DoShellExecuteResponse()

View File

@ -1,45 +1,33 @@
using ProtoBuf;
using System;
using xClient.Core.Networking;
namespace xClient.Core.Packets.ClientPackets
{
[ProtoContract]
[Serializable]
public class GetAuthenticationResponse : IPacket
{
[ProtoMember(1)]
public string Version { get; set; }
[ProtoMember(2)]
public string OperatingSystem { get; set; }
[ProtoMember(3)]
public string AccountType { get; set; }
[ProtoMember(4)]
public string Country { get; set; }
[ProtoMember(5)]
public string CountryCode { get; set; }
[ProtoMember(6)]
public string Region { get; set; }
[ProtoMember(7)]
public string City { get; set; }
[ProtoMember(8)]
public int ImageIndex { get; set; }
[ProtoMember(9)]
public string Id { get; set; }
[ProtoMember(10)]
public string Username { get; set; }
[ProtoMember(11)]
public string PCName { get; set; }
[ProtoMember(12)]
public string Tag { get; set; }
public GetAuthenticationResponse()

View File

@ -1,21 +1,17 @@
using ProtoBuf;
using System;
using xClient.Core.Networking;
namespace xClient.Core.Packets.ClientPackets
{
[ProtoContract]
[Serializable]
public class GetDesktopResponse : IPacket
{
[ProtoMember(1)]
public byte[] Image { get; set; }
[ProtoMember(2)]
public int Quality { get; set; }
[ProtoMember(3)]
public int Monitor { get; set; }
[ProtoMember(4)]
public string Resolution { get; set; }
public GetDesktopResponse()

View File

@ -1,18 +1,15 @@
using ProtoBuf;
using System;
using xClient.Core.Networking;
namespace xClient.Core.Packets.ClientPackets
{
[ProtoContract]
[Serializable]
public class GetDirectoryResponse : IPacket
{
[ProtoMember(1)]
public string[] Files { get; set; }
[ProtoMember(2)]
public string[] Folders { get; set; }
[ProtoMember(3)]
public long[] FilesSize { get; set; }
public GetDirectoryResponse()

View File

@ -1,15 +1,13 @@
using ProtoBuf;
using System;
using xClient.Core.Networking;
namespace xClient.Core.Packets.ClientPackets
{
[ProtoContract]
[Serializable]
public class GetDrivesResponse : IPacket
{
[ProtoMember(1)]
public string[] DriveDisplayName { get; set; }
[ProtoMember(2)]
public string[] RootDirectory { get; set; }
public GetDrivesResponse()

View File

@ -1,30 +1,23 @@
using ProtoBuf;
using System;
using xClient.Core.Networking;
namespace xClient.Core.Packets.ClientPackets
{
[ProtoContract]
[Serializable]
public class GetKeyloggerLogsResponse : IPacket
{
[ProtoMember(1)]
public string Filename { get; set; }
[ProtoMember(2)]
public byte[] Block { get; set; }
[ProtoMember(3)]
public int MaxBlocks { get; set; }
[ProtoMember(4)]
public int CurrentBlock { get; set; }
[ProtoMember(5)]
public string CustomMessage { get; set; }
[ProtoMember(6)]
public int Index { get; set; }
[ProtoMember(7)]
public int FileCount { get; set; }
public GetKeyloggerLogsResponse() { }

View File

@ -1,12 +1,11 @@
using ProtoBuf;
using System;
using xClient.Core.Networking;
namespace xClient.Core.Packets.ClientPackets
{
[ProtoContract]
[Serializable]
public class GetMonitorsResponse : IPacket
{
[ProtoMember(1)]
public int Number { get; set; }
public GetMonitorsResponse()

View File

@ -1,13 +1,12 @@
using System.Collections.Generic;
using ProtoBuf;
using System;
using System.Collections.Generic;
using xClient.Core.Networking;
namespace xClient.Core.Packets.ClientPackets
{
[ProtoContract]
[Serializable]
public class GetPasswordsResponse : IPacket
{
[ProtoMember(1)]
public List<string> Passwords { get; set; }
public GetPasswordsResponse()

View File

@ -1,18 +1,15 @@
using ProtoBuf;
using System;
using xClient.Core.Networking;
namespace xClient.Core.Packets.ClientPackets
{
[ProtoContract]
[Serializable]
public class GetProcessesResponse : IPacket
{
[ProtoMember(1)]
public string[] Processes { get; set; }
[ProtoMember(2)]
public int[] IDs { get; set; }
[ProtoMember(3)]
public string[] Titles { get; set; }
public GetProcessesResponse()

View File

@ -1,13 +1,12 @@
using System.Collections.Generic;
using ProtoBuf;
using System;
using System.Collections.Generic;
using xClient.Core.Networking;
namespace xClient.Core.Packets.ClientPackets
{
[ProtoContract]
[Serializable]
public class GetStartupItemsResponse : IPacket
{
[ProtoMember(1)]
public List<string> StartupItems { get; set; }
public GetStartupItemsResponse()

View File

@ -1,12 +1,11 @@
using ProtoBuf;
using System;
using xClient.Core.Networking;
namespace xClient.Core.Packets.ClientPackets
{
[ProtoContract]
[Serializable]
public class GetSystemInfoResponse : IPacket
{
[ProtoMember(1)]
public string[] SystemInfos { get; set; }
public GetSystemInfoResponse()

View File

@ -1,12 +1,11 @@
using ProtoBuf;
using System;
using xClient.Core.Networking;
namespace xClient.Core.Packets.ClientPackets
{
[ProtoContract]
[Serializable]
public class SetStatus : IPacket
{
[ProtoMember(1)]
public string Message { get; set; }
public SetStatus()

View File

@ -1,15 +1,13 @@
using ProtoBuf;
using System;
using xClient.Core.Networking;
namespace xClient.Core.Packets.ClientPackets
{
[ProtoContract]
[Serializable]
public class SetStatusFileManager : IPacket
{
[ProtoMember(1)]
public string Message { get; set; }
[ProtoMember(2)]
public bool SetLastDirectorySeen { get; set; }
public SetStatusFileManager()

View File

@ -1,13 +1,12 @@
using ProtoBuf;
using System;
using xClient.Core.Networking;
using xClient.Enums;
namespace xClient.Core.Packets.ClientPackets
{
[ProtoContract]
[Serializable]
public class SetUserStatus : IPacket
{
[ProtoMember(1)]
public UserStatus Message { get; set; }
public SetUserStatus()

View File

@ -1,9 +1,9 @@
using ProtoBuf;
using System;
using xClient.Core.Networking;
namespace xClient.Core.Packets.ServerPackets
{
[ProtoContract]
[Serializable]
public class DoClientDisconnect : IPacket
{
public DoClientDisconnect()

View File

@ -1,9 +1,9 @@
using ProtoBuf;
using System;
using xClient.Core.Networking;
namespace xClient.Core.Packets.ServerPackets
{
[ProtoContract]
[Serializable]
public class DoClientReconnect : IPacket
{
public DoClientReconnect()

View File

@ -1,9 +1,9 @@
using ProtoBuf;
using System;
using xClient.Core.Networking;
namespace xClient.Core.Packets.ServerPackets
{
[ProtoContract]
[Serializable]
public class DoClientUninstall : IPacket
{
public DoClientUninstall()

View File

@ -1,27 +1,21 @@
using ProtoBuf;
using System;
using xClient.Core.Networking;
namespace xClient.Core.Packets.ServerPackets
{
[ProtoContract]
[Serializable]
public class DoClientUpdate : IPacket
{
[ProtoMember(1)]
public int ID { get; set; }
[ProtoMember(2)]
public string DownloadURL { get; set; }
[ProtoMember(3)]
public string FileName { get; set; }
[ProtoMember(4)]
public byte[] Block { get; set; }
[ProtoMember(5)]
public int MaxBlocks { get; set; }
[ProtoMember(6)]
public int CurrentBlock { get; set; }
public DoClientUpdate()

View File

@ -1,15 +1,13 @@
using ProtoBuf;
using System;
using xClient.Core.Networking;
namespace xClient.Core.Packets.ServerPackets
{
[ProtoContract]
[Serializable]
public class DoDownloadAndExecute : IPacket
{
[ProtoMember(1)]
public string URL { get; set; }
[ProtoMember(2)]
public bool RunHidden { get; set; }
public DoDownloadAndExecute()

View File

@ -1,15 +1,13 @@
using ProtoBuf;
using System;
using xClient.Core.Networking;
namespace xClient.Core.Packets.ServerPackets
{
[ProtoContract]
[Serializable]
public class DoDownloadFile : IPacket
{
[ProtoMember(1)]
public string RemotePath { get; set; }
[ProtoMember(2)]
public int ID { get; set; }
public DoDownloadFile()

View File

@ -1,12 +1,11 @@
using ProtoBuf;
using System;
using xClient.Core.Networking;
namespace xClient.Core.Packets.ServerPackets
{
[ProtoContract]
[Serializable]
public class DoDownloadFileCancel : IPacket
{
[ProtoMember(1)]
public int ID { get; set; }
public DoDownloadFileCancel()

View File

@ -1,15 +1,13 @@
using ProtoBuf;
using System;
using xClient.Core.Networking;
namespace xClient.Core.Packets.ServerPackets
{
[ProtoContract]
[Serializable]
public class DoKeyboardEvent : IPacket
{
[ProtoMember(1)]
public byte Key { get; set; }
[ProtoMember(2)]
public bool KeyDown { get; set; }
public DoKeyboardEvent()

View File

@ -1,25 +1,20 @@
using ProtoBuf;
using System;
using xClient.Core.Networking;
using xClient.Enums;
namespace xClient.Core.Packets.ServerPackets
{
[ProtoContract]
[Serializable]
public class DoMouseEvent : IPacket
{
[ProtoMember(1)]
public MouseAction Action { get; set; }
[ProtoMember(2)]
public bool IsMouseDown { get; set; }
[ProtoMember(3)]
public int X { get; set; }
[ProtoMember(4)]
public int Y { get; set; }
[ProtoMember(5)]
public int MonitorIndex { get; set; }
public DoMouseEvent()

View File

@ -1,16 +1,14 @@
using ProtoBuf;
using System;
using xClient.Core.Networking;
using xClient.Enums;
namespace xClient.Core.Packets.ServerPackets
{
[ProtoContract]
[Serializable]
public class DoPathDelete : IPacket
{
[ProtoMember(1)]
public string Path { get; set; }
[ProtoMember(2)]
public PathType PathType { get; set; }
public DoPathDelete()

View File

@ -1,19 +1,16 @@
using ProtoBuf;
using System;
using xClient.Core.Networking;
using xClient.Enums;
namespace xClient.Core.Packets.ServerPackets
{
[ProtoContract]
[Serializable]
public class DoPathRename : IPacket
{
[ProtoMember(1)]
public string Path { get; set; }
[ProtoMember(2)]
public string NewPath { get; set; }
[ProtoMember(3)]
public PathType PathType { get; set; }
public DoPathRename()

View File

@ -1,12 +1,11 @@
using ProtoBuf;
using System;
using xClient.Core.Networking;
namespace xClient.Core.Packets.ServerPackets
{
[ProtoContract]
[Serializable]
public class DoProcessKill : IPacket
{
[ProtoMember(1)]
public int PID { get; set; }
public DoProcessKill()

View File

@ -1,12 +1,11 @@
using ProtoBuf;
using System;
using xClient.Core.Networking;
namespace xClient.Core.Packets.ServerPackets
{
[ProtoContract]
[Serializable]
public class DoProcessStart : IPacket
{
[ProtoMember(1)]
public string Processname { get; set; }
public DoProcessStart()

View File

@ -1,12 +1,11 @@
using ProtoBuf;
using System;
using xClient.Core.Networking;
namespace xClient.Core.Packets.ServerPackets
{
[ProtoContract]
[Serializable]
public class DoShellExecute : IPacket
{
[ProtoMember(1)]
public string Command { get; set; }
public DoShellExecute()

View File

@ -1,21 +1,17 @@
using ProtoBuf;
using System;
using xClient.Core.Networking;
namespace xClient.Core.Packets.ServerPackets
{
[ProtoContract]
[Serializable]
public class DoShowMessageBox : IPacket
{
[ProtoMember(1)]
public string Caption { get; set; }
[ProtoMember(2)]
public string Text { get; set; }
[ProtoMember(3)]
public string MessageboxButton { get; set; }
[ProtoMember(4)]
public string MessageboxIcon { get; set; }
public DoShowMessageBox()

View File

@ -1,13 +1,12 @@
using ProtoBuf;
using System;
using xClient.Core.Networking;
using xClient.Enums;
namespace xClient.Core.Packets.ServerPackets
{
[ProtoContract]
[Serializable]
public class DoShutdownAction : IPacket
{
[ProtoMember(1)]
public ShutdownAction Action { get; set; }
public DoShutdownAction()

View File

@ -1,18 +1,15 @@
using ProtoBuf;
using System;
using xClient.Core.Networking;
namespace xClient.Core.Packets.ServerPackets
{
[ProtoContract]
[Serializable]
public class DoStartupItemAdd : IPacket
{
[ProtoMember(1)]
public string Name { get; set; }
[ProtoMember(2)]
public string Path { get; set; }
[ProtoMember(3)]
public int Type { get; set; }
public DoStartupItemAdd()

View File

@ -1,18 +1,15 @@
using ProtoBuf;
using System;
using xClient.Core.Networking;
namespace xClient.Core.Packets.ServerPackets
{
[ProtoContract]
[Serializable]
public class DoStartupItemRemove : IPacket
{
[ProtoMember(1)]
public string Name { get; set; }
[ProtoMember(2)]
public string Path { get; set; }
[ProtoMember(3)]
public int Type { get; set; }
public DoStartupItemRemove()

View File

@ -1,27 +1,21 @@
using ProtoBuf;
using System;
using xClient.Core.Networking;
namespace xClient.Core.Packets.ServerPackets
{
[ProtoContract]
[Serializable]
public class DoUploadAndExecute : IPacket
{
[ProtoMember(1)]
public int ID { get; set; }
[ProtoMember(2)]
public string FileName { get; set; }
[ProtoMember(3)]
public byte[] Block { get; set; }
[ProtoMember(4)]
public int MaxBlocks { get; set; }
[ProtoMember(5)]
public int CurrentBlock { get; set; }
[ProtoMember(6)]
public bool RunHidden { get; set; }
public DoUploadAndExecute()

View File

@ -1,24 +1,19 @@
using ProtoBuf;
using System;
using xClient.Core.Networking;
namespace xClient.Core.Packets.ServerPackets
{
[ProtoContract]
[Serializable]
public class DoUploadFile : IPacket
{
[ProtoMember(1)]
public int ID { get; set; }
[ProtoMember(2)]
public string RemotePath { get; set; }
[ProtoMember(3)]
public byte[] Block { get; set; }
[ProtoMember(4)]
public int MaxBlocks { get; set; }
[ProtoMember(5)]
public int CurrentBlock { get; set; }
public DoUploadFile()

View File

@ -1,15 +1,13 @@
using ProtoBuf;
using System;
using xClient.Core.Networking;
namespace xClient.Core.Packets.ServerPackets
{
[ProtoContract]
[Serializable]
public class DoVisitWebsite : IPacket
{
[ProtoMember(1)]
public string URL { get; set; }
[ProtoMember(2)]
public bool Hidden { get; set; }
public DoVisitWebsite()

View File

@ -1,9 +1,9 @@
using ProtoBuf;
using System;
using xClient.Core.Networking;
namespace xClient.Core.Packets.ServerPackets
{
[ProtoContract]
[Serializable]
public class GetAuthentication : IPacket
{
public GetAuthentication()

View File

@ -1,15 +1,13 @@
using ProtoBuf;
using System;
using xClient.Core.Networking;
namespace xClient.Core.Packets.ServerPackets
{
[ProtoContract]
[Serializable]
public class GetDesktop : IPacket
{
[ProtoMember(1)]
public int Quality { get; set; }
[ProtoMember(2)]
public int Monitor { get; set; }
public GetDesktop()

View File

@ -1,12 +1,11 @@
using ProtoBuf;
using System;
using xClient.Core.Networking;
namespace xClient.Core.Packets.ServerPackets
{
[ProtoContract]
[Serializable]
public class GetDirectory : IPacket
{
[ProtoMember(1)]
public string RemotePath { get; set; }
public GetDirectory()

View File

@ -1,9 +1,9 @@
using ProtoBuf;
using System;
using xClient.Core.Networking;
namespace xClient.Core.Packets.ServerPackets
{
[ProtoContract]
[Serializable]
public class GetDrives : IPacket
{
public GetDrives()

View File

@ -1,9 +1,9 @@
using ProtoBuf;
using System;
using xClient.Core.Networking;
namespace xClient.Core.Packets.ServerPackets
{
[ProtoContract]
[Serializable]
public class GetKeyloggerLogs : IPacket
{
public GetKeyloggerLogs() { }
@ -13,4 +13,4 @@ public void Execute(Client client)
client.Send(this);
}
}
}
}

View File

@ -1,9 +1,9 @@
using ProtoBuf;
using System;
using xClient.Core.Networking;
namespace xClient.Core.Packets.ServerPackets
{
[ProtoContract]
[Serializable]
public class GetMonitors : IPacket
{
public GetMonitors()

View File

@ -1,9 +1,9 @@
using ProtoBuf;
using System;
using xClient.Core.Networking;
namespace xClient.Core.Packets.ServerPackets
{
[ProtoContract]
[Serializable]
public class GetPasswords : IPacket
{
public GetPasswords()

View File

@ -1,9 +1,9 @@
using ProtoBuf;
using System;
using xClient.Core.Networking;
namespace xClient.Core.Packets.ServerPackets
{
[ProtoContract]
[Serializable]
public class GetProcesses : IPacket
{
public GetProcesses()

View File

@ -1,9 +1,9 @@
using ProtoBuf;
using System;
using xClient.Core.Networking;
namespace xClient.Core.Packets.ServerPackets
{
[ProtoContract]
[Serializable]
public class GetStartupItems : IPacket
{
public GetStartupItems()

View File

@ -1,9 +1,9 @@
using ProtoBuf;
using System;
using xClient.Core.Networking;
namespace xClient.Core.Packets.ServerPackets
{
[ProtoContract]
[Serializable]
public class GetSystemInfo : IPacket
{
public GetSystemInfo()

View File

@ -1,26 +0,0 @@
using ProtoBuf;
using xClient.Core.Networking;
namespace xClient.Core.Packets
{
[ProtoContract]
public class UnknownPacket : IPacket
{
[ProtoMember(1)]
public IPacket Packet { get; set; }
public UnknownPacket()
{
}
public UnknownPacket(IPacket packet)
{
Packet = packet;
}
public void Execute(Client client)
{
client.Send(this);
}
}
}

View File

@ -1,588 +0,0 @@
using System;
using System.Reflection;
namespace ProtoBuf
{
internal enum TimeSpanScale
{
Days = 0,
Hours = 1,
Minutes = 2,
Seconds = 3,
Milliseconds = 4,
Ticks = 5,
MinMax = 15
}
/// <summary>
/// Provides support for common .NET types that do not have a direct representation
/// in protobuf, using the definitions from bcl.proto
/// </summary>
public
#if FX11
sealed
#else
static
#endif
class BclHelpers
{
/// <summary>
/// Creates a new instance of the specified type, bypassing the constructor.
/// </summary>
/// <param name="type">The type to create</param>
/// <returns>The new instance</returns>
/// <exception cref="NotSupportedException">If the platform does not support constructor-skipping</exception>
public static object GetUninitializedObject(Type type)
{
#if PLAT_BINARYFORMATTER && !(WINRT || PHONE8)
return System.Runtime.Serialization.FormatterServices.GetUninitializedObject(type);
#else
throw new NotSupportedException("Constructor-skipping is not supported on this platform");
#endif
}
#if FX11
private BclHelpers() { } // not a static class for C# 1.2 reasons
#endif
private const int FieldTimeSpanValue = 0x01, FieldTimeSpanScale = 0x02;
internal static readonly DateTime EpochOrigin = new DateTime(1970, 1, 1, 0, 0, 0, 0);
/// <summary>
/// Writes a TimeSpan to a protobuf stream
/// </summary>
public static void WriteTimeSpan(TimeSpan timeSpan, ProtoWriter dest)
{
if (dest == null) throw new ArgumentNullException("dest");
long value;
switch (dest.WireType)
{
case WireType.String:
case WireType.StartGroup:
TimeSpanScale scale;
value = timeSpan.Ticks;
if (timeSpan == TimeSpan.MaxValue)
{
value = 1;
scale = TimeSpanScale.MinMax;
}
else if (timeSpan == TimeSpan.MinValue)
{
value = -1;
scale = TimeSpanScale.MinMax;
}
else if (value%TimeSpan.TicksPerDay == 0)
{
scale = TimeSpanScale.Days;
value /= TimeSpan.TicksPerDay;
}
else if (value%TimeSpan.TicksPerHour == 0)
{
scale = TimeSpanScale.Hours;
value /= TimeSpan.TicksPerHour;
}
else if (value%TimeSpan.TicksPerMinute == 0)
{
scale = TimeSpanScale.Minutes;
value /= TimeSpan.TicksPerMinute;
}
else if (value%TimeSpan.TicksPerSecond == 0)
{
scale = TimeSpanScale.Seconds;
value /= TimeSpan.TicksPerSecond;
}
else if (value%TimeSpan.TicksPerMillisecond == 0)
{
scale = TimeSpanScale.Milliseconds;
value /= TimeSpan.TicksPerMillisecond;
}
else
{
scale = TimeSpanScale.Ticks;
}
SubItemToken token = ProtoWriter.StartSubItem(null, dest);
if (value != 0)
{
ProtoWriter.WriteFieldHeader(FieldTimeSpanValue, WireType.SignedVariant, dest);
ProtoWriter.WriteInt64(value, dest);
}
if (scale != TimeSpanScale.Days)
{
ProtoWriter.WriteFieldHeader(FieldTimeSpanScale, WireType.Variant, dest);
ProtoWriter.WriteInt32((int) scale, dest);
}
ProtoWriter.EndSubItem(token, dest);
break;
case WireType.Fixed64:
ProtoWriter.WriteInt64(timeSpan.Ticks, dest);
break;
default:
throw new ProtoException("Unexpected wire-type: " + dest.WireType.ToString());
}
}
/// <summary>
/// Parses a TimeSpan from a protobuf stream
/// </summary>
public static TimeSpan ReadTimeSpan(ProtoReader source)
{
long ticks = ReadTimeSpanTicks(source);
if (ticks == long.MinValue) return TimeSpan.MinValue;
if (ticks == long.MaxValue) return TimeSpan.MaxValue;
return TimeSpan.FromTicks(ticks);
}
/// <summary>
/// Parses a DateTime from a protobuf stream
/// </summary>
public static DateTime ReadDateTime(ProtoReader source)
{
long ticks = ReadTimeSpanTicks(source);
if (ticks == long.MinValue) return DateTime.MinValue;
if (ticks == long.MaxValue) return DateTime.MaxValue;
return EpochOrigin.AddTicks(ticks);
}
/// <summary>
/// Writes a DateTime to a protobuf stream
/// </summary>
public static void WriteDateTime(DateTime value, ProtoWriter dest)
{
if (dest == null) throw new ArgumentNullException("dest");
TimeSpan delta;
switch (dest.WireType)
{
case WireType.StartGroup:
case WireType.String:
if (value == DateTime.MaxValue)
{
delta = TimeSpan.MaxValue;
}
else if (value == DateTime.MinValue)
{
delta = TimeSpan.MinValue;
}
else
{
delta = value - EpochOrigin;
}
break;
default:
delta = value - EpochOrigin;
break;
}
WriteTimeSpan(delta, dest);
}
private static long ReadTimeSpanTicks(ProtoReader source)
{
switch (source.WireType)
{
case WireType.String:
case WireType.StartGroup:
SubItemToken token = ProtoReader.StartSubItem(source);
int fieldNumber;
TimeSpanScale scale = TimeSpanScale.Days;
long value = 0;
while ((fieldNumber = source.ReadFieldHeader()) > 0)
{
switch (fieldNumber)
{
case FieldTimeSpanScale:
scale = (TimeSpanScale) source.ReadInt32();
break;
case FieldTimeSpanValue:
source.Assert(WireType.SignedVariant);
value = source.ReadInt64();
break;
default:
source.SkipField();
break;
}
}
ProtoReader.EndSubItem(token, source);
switch (scale)
{
case TimeSpanScale.Days:
return value*TimeSpan.TicksPerDay;
case TimeSpanScale.Hours:
return value*TimeSpan.TicksPerHour;
case TimeSpanScale.Minutes:
return value*TimeSpan.TicksPerMinute;
case TimeSpanScale.Seconds:
return value*TimeSpan.TicksPerSecond;
case TimeSpanScale.Milliseconds:
return value*TimeSpan.TicksPerMillisecond;
case TimeSpanScale.Ticks:
return value;
case TimeSpanScale.MinMax:
switch (value)
{
case 1:
return long.MaxValue;
case -1:
return long.MinValue;
default:
throw new ProtoException("Unknown min/max value: " + value.ToString());
}
default:
throw new ProtoException("Unknown timescale: " + scale.ToString());
}
case WireType.Fixed64:
return source.ReadInt64();
default:
throw new ProtoException("Unexpected wire-type: " + source.WireType.ToString());
}
}
private const int FieldDecimalLow = 0x01, FieldDecimalHigh = 0x02, FieldDecimalSignScale = 0x03;
/// <summary>
/// Parses a decimal from a protobuf stream
/// </summary>
public static decimal ReadDecimal(ProtoReader reader)
{
ulong low = 0;
uint high = 0;
uint signScale = 0;
int fieldNumber;
SubItemToken token = ProtoReader.StartSubItem(reader);
while ((fieldNumber = reader.ReadFieldHeader()) > 0)
{
switch (fieldNumber)
{
case FieldDecimalLow:
low = reader.ReadUInt64();
break;
case FieldDecimalHigh:
high = reader.ReadUInt32();
break;
case FieldDecimalSignScale:
signScale = reader.ReadUInt32();
break;
default:
reader.SkipField();
break;
}
}
ProtoReader.EndSubItem(token, reader);
if (low == 0 && high == 0) return decimal.Zero;
int lo = (int) (low & 0xFFFFFFFFL),
mid = (int) ((low >> 32) & 0xFFFFFFFFL),
hi = (int) high;
bool isNeg = (signScale & 0x0001) == 0x0001;
byte scale = (byte) ((signScale & 0x01FE) >> 1);
return new decimal(lo, mid, hi, isNeg, scale);
}
/// <summary>
/// Writes a decimal to a protobuf stream
/// </summary>
public static void WriteDecimal(decimal value, ProtoWriter writer)
{
int[] bits = decimal.GetBits(value);
ulong a = ((ulong) bits[1]) << 32, b = ((ulong) bits[0]) & 0xFFFFFFFFL;
ulong low = a | b;
uint high = (uint) bits[2];
uint signScale = (uint) (((bits[3] >> 15) & 0x01FE) | ((bits[3] >> 31) & 0x0001));
SubItemToken token = ProtoWriter.StartSubItem(null, writer);
if (low != 0)
{
ProtoWriter.WriteFieldHeader(FieldDecimalLow, WireType.Variant, writer);
ProtoWriter.WriteUInt64(low, writer);
}
if (high != 0)
{
ProtoWriter.WriteFieldHeader(FieldDecimalHigh, WireType.Variant, writer);
ProtoWriter.WriteUInt32(high, writer);
}
if (signScale != 0)
{
ProtoWriter.WriteFieldHeader(FieldDecimalSignScale, WireType.Variant, writer);
ProtoWriter.WriteUInt32(signScale, writer);
}
ProtoWriter.EndSubItem(token, writer);
}
private const int FieldGuidLow = 1, FieldGuidHigh = 2;
/// <summary>
/// Writes a Guid to a protobuf stream
/// </summary>
public static void WriteGuid(Guid value, ProtoWriter dest)
{
byte[] blob = value.ToByteArray();
SubItemToken token = ProtoWriter.StartSubItem(null, dest);
if (value != Guid.Empty)
{
ProtoWriter.WriteFieldHeader(FieldGuidLow, WireType.Fixed64, dest);
ProtoWriter.WriteBytes(blob, 0, 8, dest);
ProtoWriter.WriteFieldHeader(FieldGuidHigh, WireType.Fixed64, dest);
ProtoWriter.WriteBytes(blob, 8, 8, dest);
}
ProtoWriter.EndSubItem(token, dest);
}
/// <summary>
/// Parses a Guid from a protobuf stream
/// </summary>
public static Guid ReadGuid(ProtoReader source)
{
ulong low = 0, high = 0;
int fieldNumber;
SubItemToken token = ProtoReader.StartSubItem(source);
while ((fieldNumber = source.ReadFieldHeader()) > 0)
{
switch (fieldNumber)
{
case FieldGuidLow:
low = source.ReadUInt64();
break;
case FieldGuidHigh:
high = source.ReadUInt64();
break;
default:
source.SkipField();
break;
}
}
ProtoReader.EndSubItem(token, source);
if (low == 0 && high == 0) return Guid.Empty;
uint a = (uint) (low >> 32), b = (uint) low, c = (uint) (high >> 32), d = (uint) high;
return new Guid((int) b, (short) a, (short) (a >> 16),
(byte) d, (byte) (d >> 8), (byte) (d >> 16), (byte) (d >> 24),
(byte) c, (byte) (c >> 8), (byte) (c >> 16), (byte) (c >> 24));
}
private const int
FieldExistingObjectKey = 1,
FieldNewObjectKey = 2,
FieldExistingTypeKey = 3,
FieldNewTypeKey = 4,
FieldTypeName = 8,
FieldObject = 10;
/// <summary>
/// Optional behaviours that introduce .NET-specific functionality
/// </summary>
[Flags]
public enum NetObjectOptions : byte
{
/// <summary>
/// No special behaviour
/// </summary>
None = 0,
/// <summary>
/// Enables full object-tracking/full-graph support.
/// </summary>
AsReference = 1,
/// <summary>
/// Embeds the type information into the stream, allowing usage with types not known in advance.
/// </summary>
DynamicType = 2,
/// <summary>
/// If false, the constructor for the type is bypassed during deserialization, meaning any field initializers
/// or other initialization code is skipped.
/// </summary>
UseConstructor = 4,
/// <summary>
/// Should the object index be reserved, rather than creating an object promptly
/// </summary>
LateSet = 8
}
/// <summary>
/// Reads an *implementation specific* bundled .NET object, including (as options) type-metadata, identity/re-use, etc.
/// </summary>
public static object ReadNetObject(object value, ProtoReader source, int key, Type type,
NetObjectOptions options)
{
#if FEAT_IKVM
throw new NotSupportedException();
#else
SubItemToken token = ProtoReader.StartSubItem(source);
int fieldNumber;
int newObjectKey = -1, newTypeKey = -1, tmp;
while ((fieldNumber = source.ReadFieldHeader()) > 0)
{
switch (fieldNumber)
{
case FieldExistingObjectKey:
tmp = source.ReadInt32();
value = source.NetCache.GetKeyedObject(tmp);
break;
case FieldNewObjectKey:
newObjectKey = source.ReadInt32();
break;
case FieldExistingTypeKey:
tmp = source.ReadInt32();
type = (Type) source.NetCache.GetKeyedObject(tmp);
key = source.GetTypeKey(ref type);
break;
case FieldNewTypeKey:
newTypeKey = source.ReadInt32();
break;
case FieldTypeName:
string typeName = source.ReadString();
type = source.DeserializeType(typeName);
if (type == null)
{
throw new ProtoException("Unable to resolve type: " + typeName +
" (you can use the TypeModel.DynamicTypeFormatting event to provide a custom mapping)");
}
if (type == typeof (string))
{
key = -1;
}
else
{
key = source.GetTypeKey(ref type);
if (key < 0)
throw new InvalidOperationException("Dynamic type is not a contract-type: " + type.Name);
}
break;
case FieldObject:
bool isString = type == typeof (string);
bool wasNull = value == null;
bool lateSet = wasNull && (isString || ((options & NetObjectOptions.LateSet) != 0));
if (newObjectKey >= 0 && !lateSet)
{
if (value == null)
{
source.TrapNextObject(newObjectKey);
}
else
{
source.NetCache.SetKeyedObject(newObjectKey, value);
}
if (newTypeKey >= 0) source.NetCache.SetKeyedObject(newTypeKey, type);
}
object oldValue = value;
if (isString)
{
value = source.ReadString();
}
else
{
value = ProtoReader.ReadTypedObject(oldValue, key, source, type);
}
if (newObjectKey >= 0)
{
if (wasNull && !lateSet)
{
// this both ensures (via exception) that it *was* set, and makes sure we don't shout
// about changed references
oldValue = source.NetCache.GetKeyedObject(newObjectKey);
}
if (lateSet)
{
source.NetCache.SetKeyedObject(newObjectKey, value);
if (newTypeKey >= 0) source.NetCache.SetKeyedObject(newTypeKey, type);
}
}
if (newObjectKey >= 0 && !lateSet && !ReferenceEquals(oldValue, value))
{
throw new ProtoException(
"A reference-tracked object changed reference during deserialization");
}
if (newObjectKey < 0 && newTypeKey >= 0)
{
// have a new type, but not a new object
source.NetCache.SetKeyedObject(newTypeKey, type);
}
break;
default:
source.SkipField();
break;
}
}
if (newObjectKey >= 0 && (options & NetObjectOptions.AsReference) == 0)
{
throw new ProtoException("Object key in input stream, but reference-tracking was not expected");
}
ProtoReader.EndSubItem(token, source);
return value;
#endif
}
/// <summary>
/// Writes an *implementation specific* bundled .NET object, including (as options) type-metadata, identity/re-use, etc.
/// </summary>
public static void WriteNetObject(object value, ProtoWriter dest, int key, NetObjectOptions options)
{
#if FEAT_IKVM
throw new NotSupportedException();
#else
if (dest == null) throw new ArgumentNullException("dest");
bool dynamicType = (options & NetObjectOptions.DynamicType) != 0,
asReference = (options & NetObjectOptions.AsReference) != 0;
WireType wireType = dest.WireType;
SubItemToken token = ProtoWriter.StartSubItem(null, dest);
bool writeObject = true;
if (asReference)
{
bool existing;
int objectKey = dest.NetCache.AddObjectKey(value, out existing);
ProtoWriter.WriteFieldHeader(existing ? FieldExistingObjectKey : FieldNewObjectKey, WireType.Variant,
dest);
ProtoWriter.WriteInt32(objectKey, dest);
if (existing)
{
writeObject = false;
}
}
if (writeObject)
{
if (dynamicType)
{
bool existing;
Type type = value.GetType();
if (!(value is string))
{
key = dest.GetTypeKey(ref type);
if (key < 0)
throw new InvalidOperationException("Dynamic type is not a contract-type: " + type.Name);
}
int typeKey = dest.NetCache.AddObjectKey(type, out existing);
ProtoWriter.WriteFieldHeader(existing ? FieldExistingTypeKey : FieldNewTypeKey, WireType.Variant,
dest);
ProtoWriter.WriteInt32(typeKey, dest);
if (!existing)
{
ProtoWriter.WriteFieldHeader(FieldTypeName, WireType.String, dest);
ProtoWriter.WriteString(dest.SerializeType(type), dest);
}
}
ProtoWriter.WriteFieldHeader(FieldObject, wireType, dest);
if (value is string)
{
ProtoWriter.WriteString((string) value, dest);
}
else
{
ProtoWriter.WriteObject(value, key, dest);
}
}
ProtoWriter.EndSubItem(token, dest);
#endif
}
}
}

View File

@ -1,80 +0,0 @@
using System;
using System.IO;
namespace ProtoBuf
{
/// <summary>
/// Provides a simple buffer-based implementation of an <see cref="IExtension">extension</see> object.
/// </summary>
public sealed class BufferExtension : IExtension
{
private byte[] buffer;
int IExtension.GetLength()
{
return buffer == null ? 0 : buffer.Length;
}
Stream IExtension.BeginAppend()
{
return new MemoryStream();
}
void IExtension.EndAppend(Stream stream, bool commit)
{
using (stream)
{
int len;
if (commit && (len = (int) stream.Length) > 0)
{
using (MemoryStream ms = (MemoryStream) stream)
{
if (buffer == null)
{
// allocate new buffer
buffer = ms.ToArray();
}
else
{
// resize and copy the data
// note: Array.Resize not available on CF
int offset = buffer.Length;
byte[] tmp = new byte[offset + len];
Helpers.BlockCopy(buffer, 0, tmp, 0, offset);
#if PORTABLE || WINRT // no GetBuffer() - fine, we'll use Read instead
int bytesRead;
long oldPos = ms.Position;
ms.Position = 0;
while (len > 0 && (bytesRead = ms.Read(tmp, offset, len)) > 0)
{
len -= bytesRead;
offset += bytesRead;
}
if(len != 0) throw new EndOfStreamException();
ms.Position = oldPos;
#else
Helpers.BlockCopy(ms.GetBuffer(), 0, tmp, offset, len);
#endif
buffer = tmp;
}
}
}
}
}
Stream IExtension.BeginQuery()
{
return buffer == null ? Stream.Null : new MemoryStream(buffer);
}
void IExtension.EndQuery(Stream stream)
{
// Clean up
if (stream != null)
{
stream.Dispose();
}
}
}
}

View File

@ -1,109 +0,0 @@
using System.Threading;
namespace ProtoBuf
{
internal sealed class BufferPool
{
internal static void Flush()
{
#if PLAT_NO_INTERLOCKED
lock(pool)
{
for (int i = 0; i < pool.Length; i++) pool[i] = null;
}
#else
for (int i = 0; i < pool.Length; i++)
{
Interlocked.Exchange(ref pool[i], null); // and drop the old value on the floor
}
#endif
}
private BufferPool()
{
}
private const int PoolSize = 20;
internal const int BufferLength = 1024;
private static readonly object[] pool = new object[PoolSize];
internal static byte[] GetBuffer()
{
object tmp;
#if PLAT_NO_INTERLOCKED
lock(pool)
{
for (int i = 0; i < pool.Length; i++)
{
if((tmp = pool[i]) != null)
{
pool[i] = null;
return (byte[])tmp;
}
}
}
#else
for (int i = 0; i < pool.Length; i++)
{
if ((tmp = Interlocked.Exchange(ref pool[i], null)) != null) return (byte[]) tmp;
}
#endif
return new byte[BufferLength];
}
internal static void ResizeAndFlushLeft(ref byte[] buffer, int toFitAtLeastBytes, int copyFromIndex,
int copyBytes)
{
Helpers.DebugAssert(buffer != null);
Helpers.DebugAssert(toFitAtLeastBytes > buffer.Length);
Helpers.DebugAssert(copyFromIndex >= 0);
Helpers.DebugAssert(copyBytes >= 0);
// try doubling, else match
int newLength = buffer.Length*2;
if (newLength < toFitAtLeastBytes) newLength = toFitAtLeastBytes;
byte[] newBuffer = new byte[newLength];
if (copyBytes > 0)
{
Helpers.BlockCopy(buffer, copyFromIndex, newBuffer, 0, copyBytes);
}
if (buffer.Length == BufferPool.BufferLength)
{
BufferPool.ReleaseBufferToPool(ref buffer);
}
buffer = newBuffer;
}
internal static void ReleaseBufferToPool(ref byte[] buffer)
{
if (buffer == null) return;
if (buffer.Length == BufferLength)
{
#if PLAT_NO_INTERLOCKED
lock (pool)
{
for (int i = 0; i < pool.Length; i++)
{
if(pool[i] == null)
{
pool[i] = buffer;
break;
}
}
}
#else
for (int i = 0; i < pool.Length; i++)
{
if (Interlocked.CompareExchange(ref pool[i], buffer, null) == null)
{
break; // found a null; swapped it in
}
}
#endif
}
// if no space, just drop it on the floor
buffer = null;
}
}
}

View File

@ -1,41 +0,0 @@
using System;
using System.ComponentModel;
namespace ProtoBuf
{
/// <summary>Specifies a method on the root-contract in an hierarchy to be invoked before serialization.</summary>
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)]
#if !CF && !SILVERLIGHT && !MONODROID && !WINRT && !IOS && !PORTABLE
[ImmutableObject(true)]
#endif
public sealed class ProtoBeforeSerializationAttribute : Attribute
{
}
/// <summary>Specifies a method on the root-contract in an hierarchy to be invoked after serialization.</summary>
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)]
#if !CF && !SILVERLIGHT && !MONODROID && !WINRT && !IOS && !PORTABLE
[ImmutableObject(true)]
#endif
public sealed class ProtoAfterSerializationAttribute : Attribute
{
}
/// <summary>Specifies a method on the root-contract in an hierarchy to be invoked before deserialization.</summary>
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)]
#if !CF && !SILVERLIGHT && !MONODROID && !WINRT && !IOS && !PORTABLE
[ImmutableObject(true)]
#endif
public sealed class ProtoBeforeDeserializationAttribute : Attribute
{
}
/// <summary>Specifies a method on the root-contract in an hierarchy to be invoked after deserialization.</summary>
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)]
#if !CF && !SILVERLIGHT && !MONODROID && !WINRT && !IOS && !PORTABLE
[ImmutableObject(true)]
#endif
public sealed class ProtoAfterDeserializationAttribute : Attribute
{
}
}

View File

@ -1,41 +0,0 @@
namespace ProtoBuf
{
/// <summary>
/// Sub-format to use when serializing/deserializing data
/// </summary>
public enum DataFormat
{
/// <summary>
/// Uses the default encoding for the data-type.
/// </summary>
Default,
/// <summary>
/// When applied to signed integer-based data (including Decimal), this
/// indicates that zigzag variant encoding will be used. This means that values
/// with small magnitude (regardless of sign) take a small amount
/// of space to encode.
/// </summary>
ZigZag,
/// <summary>
/// When applied to signed integer-based data (including Decimal), this
/// indicates that two's-complement variant encoding will be used.
/// This means that any -ve number will take 10 bytes (even for 32-bit),
/// so should only be used for compatibility.
/// </summary>
TwosComplement,
/// <summary>
/// When applied to signed integer-based data (including Decimal), this
/// indicates that a fixed amount of space will be used.
/// </summary>
FixedSize,
/// <summary>
/// When applied to a sub-message, indicates that the value should be treated
/// as group-delimited.
/// </summary>
Group
}
}

View File

@ -1,294 +0,0 @@
#if !NO_GENERICS
using System.Collections.Generic;
#endif
using ProtoBuf.Meta;
using System.Collections;
namespace ProtoBuf
{
/// <summary>
/// Simple base class for supporting unexpected fields allowing
/// for loss-less round-tips/merge, even if the data is not understod.
/// The additional fields are (by default) stored in-memory in a buffer.
/// </summary>
/// <remarks>As an example of an alternative implementation, you might
/// choose to use the file system (temporary files) as the back-end, tracking
/// only the paths [such an object would ideally be IDisposable and use
/// a finalizer to ensure that the files are removed].</remarks>
/// <seealso cref="IExtensible"/>
public abstract class Extensible : IExtensible
{
// note: not marked ProtoContract - no local state, and can't
// predict sub-classes
private IExtension extensionObject;
IExtension IExtensible.GetExtensionObject(bool createIfMissing)
{
return GetExtensionObject(createIfMissing);
}
/// <summary>
/// Retrieves the <see cref="IExtension">extension</see> object for the current
/// instance, optionally creating it if it does not already exist.
/// </summary>
/// <param name="createIfMissing">Should a new extension object be
/// created if it does not already exist?</param>
/// <returns>The extension object if it exists (or was created), or null
/// if the extension object does not exist or is not available.</returns>
/// <remarks>The <c>createIfMissing</c> argument is false during serialization,
/// and true during deserialization upon encountering unexpected fields.</remarks>
protected virtual IExtension GetExtensionObject(bool createIfMissing)
{
return GetExtensionObject(ref extensionObject, createIfMissing);
}
/// <summary>
/// Provides a simple, default implementation for <see cref="IExtension">extension</see> support,
/// optionally creating it if it does not already exist. Designed to be called by
/// classes implementing <see cref="IExtensible"/>.
/// </summary>
/// <param name="createIfMissing">Should a new extension object be
/// created if it does not already exist?</param>
/// <param name="extensionObject">The extension field to check (and possibly update).</param>
/// <returns>The extension object if it exists (or was created), or null
/// if the extension object does not exist or is not available.</returns>
/// <remarks>The <c>createIfMissing</c> argument is false during serialization,
/// and true during deserialization upon encountering unexpected fields.</remarks>
public static IExtension GetExtensionObject(ref IExtension extensionObject, bool createIfMissing)
{
if (createIfMissing && extensionObject == null)
{
extensionObject = new BufferExtension();
}
return extensionObject;
}
#if !NO_RUNTIME && !NO_GENERICS
/// <summary>
/// Appends the value as an additional (unexpected) data-field for the instance.
/// Note that for non-repeated sub-objects, this equates to a merge operation;
/// for repeated sub-objects this adds a new instance to the set; for simple
/// values the new value supercedes the old value.
/// </summary>
/// <remarks>Note that appending a value does not remove the old value from
/// the stream; avoid repeatedly appending values for the same field.</remarks>
/// <typeparam name="TValue">The type of the value to append.</typeparam>
/// <param name="instance">The extensible object to append the value to.</param>
/// <param name="tag">The field identifier; the tag should not be defined as a known data-field for the instance.</param>
/// <param name="value">The value to append.</param>
public static void AppendValue<TValue>(IExtensible instance, int tag, TValue value)
{
AppendValue<TValue>(instance, tag, DataFormat.Default, value);
}
/// <summary>
/// Appends the value as an additional (unexpected) data-field for the instance.
/// Note that for non-repeated sub-objects, this equates to a merge operation;
/// for repeated sub-objects this adds a new instance to the set; for simple
/// values the new value supercedes the old value.
/// </summary>
/// <remarks>Note that appending a value does not remove the old value from
/// the stream; avoid repeatedly appending values for the same field.</remarks>
/// <typeparam name="TValue">The data-type of the field.</typeparam>
/// <param name="format">The data-format to use when encoding the value.</param>
/// <param name="instance">The extensible object to append the value to.</param>
/// <param name="tag">The field identifier; the tag should not be defined as a known data-field for the instance.</param>
/// <param name="value">The value to append.</param>
public static void AppendValue<TValue>(IExtensible instance, int tag, DataFormat format, TValue value)
{
ExtensibleUtil.AppendExtendValue(RuntimeTypeModel.Default, instance, tag, format, value);
}
/// <summary>
/// Queries an extensible object for an additional (unexpected) data-field for the instance.
/// The value returned is the composed value after merging any duplicated content; if the
/// value is "repeated" (a list), then use GetValues instead.
/// </summary>
/// <typeparam name="TValue">The data-type of the field.</typeparam>
/// <param name="instance">The extensible object to obtain the value from.</param>
/// <param name="tag">The field identifier; the tag should not be defined as a known data-field for the instance.</param>
/// <returns>The effective value of the field, or the default value if not found.</returns>
public static TValue GetValue<TValue>(IExtensible instance, int tag)
{
return GetValue<TValue>(instance, tag, DataFormat.Default);
}
/// <summary>
/// Queries an extensible object for an additional (unexpected) data-field for the instance.
/// The value returned is the composed value after merging any duplicated content; if the
/// value is "repeated" (a list), then use GetValues instead.
/// </summary>
/// <typeparam name="TValue">The data-type of the field.</typeparam>
/// <param name="instance">The extensible object to obtain the value from.</param>
/// <param name="tag">The field identifier; the tag should not be defined as a known data-field for the instance.</param>
/// <param name="format">The data-format to use when decoding the value.</param>
/// <returns>The effective value of the field, or the default value if not found.</returns>
public static TValue GetValue<TValue>(IExtensible instance, int tag, DataFormat format)
{
TValue value;
TryGetValue<TValue>(instance, tag, format, out value);
return value;
}
/// <summary>
/// Queries an extensible object for an additional (unexpected) data-field for the instance.
/// The value returned (in "value") is the composed value after merging any duplicated content;
/// if the value is "repeated" (a list), then use GetValues instead.
/// </summary>
/// <typeparam name="TValue">The data-type of the field.</typeparam>
/// <param name="value">The effective value of the field, or the default value if not found.</param>
/// <param name="instance">The extensible object to obtain the value from.</param>
/// <param name="tag">The field identifier; the tag should not be defined as a known data-field for the instance.</param>
/// <returns>True if data for the field was present, false otherwise.</returns>
public static bool TryGetValue<TValue>(IExtensible instance, int tag, out TValue value)
{
return TryGetValue<TValue>(instance, tag, DataFormat.Default, out value);
}
/// <summary>
/// Queries an extensible object for an additional (unexpected) data-field for the instance.
/// The value returned (in "value") is the composed value after merging any duplicated content;
/// if the value is "repeated" (a list), then use GetValues instead.
/// </summary>
/// <typeparam name="TValue">The data-type of the field.</typeparam>
/// <param name="value">The effective value of the field, or the default value if not found.</param>
/// <param name="instance">The extensible object to obtain the value from.</param>
/// <param name="tag">The field identifier; the tag should not be defined as a known data-field for the instance.</param>
/// <param name="format">The data-format to use when decoding the value.</param>
/// <returns>True if data for the field was present, false otherwise.</returns>
public static bool TryGetValue<TValue>(IExtensible instance, int tag, DataFormat format, out TValue value)
{
return TryGetValue<TValue>(instance, tag, format, false, out value);
}
/// <summary>
/// Queries an extensible object for an additional (unexpected) data-field for the instance.
/// The value returned (in "value") is the composed value after merging any duplicated content;
/// if the value is "repeated" (a list), then use GetValues instead.
/// </summary>
/// <typeparam name="TValue">The data-type of the field.</typeparam>
/// <param name="value">The effective value of the field, or the default value if not found.</param>
/// <param name="instance">The extensible object to obtain the value from.</param>
/// <param name="tag">The field identifier; the tag should not be defined as a known data-field for the instance.</param>
/// <param name="format">The data-format to use when decoding the value.</param>
/// <param name="allowDefinedTag">Allow tags that are present as part of the definition; for example, to query unknown enum values.</param>
/// <returns>True if data for the field was present, false otherwise.</returns>
public static bool TryGetValue<TValue>(IExtensible instance, int tag, DataFormat format, bool allowDefinedTag,
out TValue value)
{
value = default(TValue);
bool set = false;
foreach (
TValue val in ExtensibleUtil.GetExtendedValues<TValue>(instance, tag, format, true, allowDefinedTag))
{
// expecting at most one yield...
// but don't break; need to read entire stream
value = val;
set = true;
}
return set;
}
/// <summary>
/// Queries an extensible object for an additional (unexpected) data-field for the instance.
/// Each occurrence of the field is yielded separately, making this usage suitable for "repeated"
/// (list) fields.
/// </summary>
/// <remarks>The extended data is processed lazily as the enumerator is iterated.</remarks>
/// <typeparam name="TValue">The data-type of the field.</typeparam>
/// <param name="instance">The extensible object to obtain the value from.</param>
/// <param name="tag">The field identifier; the tag should not be defined as a known data-field for the instance.</param>
/// <returns>An enumerator that yields each occurrence of the field.</returns>
public static IEnumerable<TValue> GetValues<TValue>(IExtensible instance, int tag)
{
return ExtensibleUtil.GetExtendedValues<TValue>(instance, tag, DataFormat.Default, false, false);
}
/// <summary>
/// Queries an extensible object for an additional (unexpected) data-field for the instance.
/// Each occurrence of the field is yielded separately, making this usage suitable for "repeated"
/// (list) fields.
/// </summary>
/// <remarks>The extended data is processed lazily as the enumerator is iterated.</remarks>
/// <typeparam name="TValue">The data-type of the field.</typeparam>
/// <param name="instance">The extensible object to obtain the value from.</param>
/// <param name="tag">The field identifier; the tag should not be defined as a known data-field for the instance.</param>
/// <param name="format">The data-format to use when decoding the value.</param>
/// <returns>An enumerator that yields each occurrence of the field.</returns>
public static IEnumerable<TValue> GetValues<TValue>(IExtensible instance, int tag, DataFormat format)
{
return ExtensibleUtil.GetExtendedValues<TValue>(instance, tag, format, false, false);
}
#endif
/// <summary>
/// Queries an extensible object for an additional (unexpected) data-field for the instance.
/// The value returned (in "value") is the composed value after merging any duplicated content;
/// if the value is "repeated" (a list), then use GetValues instead.
/// </summary>
/// <param name="type">The data-type of the field.</param>
/// <param name="model">The model to use for configuration.</param>
/// <param name="value">The effective value of the field, or the default value if not found.</param>
/// <param name="instance">The extensible object to obtain the value from.</param>
/// <param name="tag">The field identifier; the tag should not be defined as a known data-field for the instance.</param>
/// <param name="format">The data-format to use when decoding the value.</param>
/// <param name="allowDefinedTag">Allow tags that are present as part of the definition; for example, to query unknown enum values.</param>
/// <returns>True if data for the field was present, false otherwise.</returns>
public static bool TryGetValue(TypeModel model, System.Type type, IExtensible instance, int tag,
DataFormat format, bool allowDefinedTag, out object value)
{
value = null;
bool set = false;
foreach (
object val in
ExtensibleUtil.GetExtendedValues(model, type, instance, tag, format, true, allowDefinedTag))
{
// expecting at most one yield...
// but don't break; need to read entire stream
value = val;
set = true;
}
return set;
}
/// <summary>
/// Queries an extensible object for an additional (unexpected) data-field for the instance.
/// Each occurrence of the field is yielded separately, making this usage suitable for "repeated"
/// (list) fields.
/// </summary>
/// <remarks>The extended data is processed lazily as the enumerator is iterated.</remarks>
/// <param name="model">The model to use for configuration.</param>
/// <param name="type">The data-type of the field.</param>
/// <param name="instance">The extensible object to obtain the value from.</param>
/// <param name="tag">The field identifier; the tag should not be defined as a known data-field for the instance.</param>
/// <param name="format">The data-format to use when decoding the value.</param>
/// <returns>An enumerator that yields each occurrence of the field.</returns>
public static IEnumerable GetValues(TypeModel model, System.Type type, IExtensible instance, int tag,
DataFormat format)
{
return ExtensibleUtil.GetExtendedValues(model, type, instance, tag, format, false, false);
}
/// <summary>
/// Appends the value as an additional (unexpected) data-field for the instance.
/// Note that for non-repeated sub-objects, this equates to a merge operation;
/// for repeated sub-objects this adds a new instance to the set; for simple
/// values the new value supercedes the old value.
/// </summary>
/// <remarks>Note that appending a value does not remove the old value from
/// the stream; avoid repeatedly appending values for the same field.</remarks>
/// <param name="model">The model to use for configuration.</param>
/// <param name="format">The data-format to use when encoding the value.</param>
/// <param name="instance">The extensible object to append the value to.</param>
/// <param name="tag">The field identifier; the tag should not be defined as a known data-field for the instance.</param>
/// <param name="value">The value to append.</param>
public static void AppendValue(TypeModel model, IExtensible instance, int tag, DataFormat format, object value)
{
ExtensibleUtil.AppendExtendValue(model, instance, tag, format, value);
}
}
}

View File

@ -1,167 +0,0 @@
using System;
using System.Collections;
#if !NO_GENERICS
using System.Collections.Generic;
#endif
using System.IO;
using ProtoBuf.Meta;
namespace ProtoBuf
{
/// <summary>
/// This class acts as an internal wrapper allowing us to do a dynamic
/// methodinfo invoke; an't put into Serializer as don't want on public
/// API; can't put into Serializer&lt;T&gt; since we need to invoke
/// accross classes, which isn't allowed in Silverlight)
/// </summary>
internal
#if FX11
sealed
#else
static
#endif
class ExtensibleUtil
{
#if FX11
private ExtensibleUtil() { } // not a static class for C# 1.2 reasons
#endif
#if !NO_RUNTIME && !NO_GENERICS
/// <summary>
/// All this does is call GetExtendedValuesTyped with the correct type for "instance";
/// this ensures that we don't get issues with subclasses declaring conflicting types -
/// the caller must respect the fields defined for the type they pass in.
/// </summary>
internal static IEnumerable<TValue> GetExtendedValues<TValue>(IExtensible instance, int tag, DataFormat format,
bool singleton, bool allowDefinedTag)
{
foreach (
TValue value in
GetExtendedValues(RuntimeTypeModel.Default, typeof (TValue), instance, tag, format, singleton,
allowDefinedTag))
{
yield return value;
}
}
#endif
/// <summary>
/// All this does is call GetExtendedValuesTyped with the correct type for "instance";
/// this ensures that we don't get issues with subclasses declaring conflicting types -
/// the caller must respect the fields defined for the type they pass in.
/// </summary>
internal static IEnumerable GetExtendedValues(TypeModel model, Type type, IExtensible instance, int tag,
DataFormat format, bool singleton, bool allowDefinedTag)
{
#if FEAT_IKVM
throw new NotSupportedException();
#else
if (instance == null) throw new ArgumentNullException("instance");
if (tag <= 0) throw new ArgumentOutOfRangeException("tag");
IExtension extn = instance.GetExtensionObject(false);
if (extn == null)
{
#if FX11
return new object[0];
#else
yield break;
#endif
}
#if FX11
BasicList result = new BasicList();
#endif
Stream stream = extn.BeginQuery();
object value = null;
ProtoReader reader = null;
try
{
SerializationContext ctx = new SerializationContext();
reader = ProtoReader.Create(stream, model, ctx, ProtoReader.TO_EOF);
while (
model.TryDeserializeAuxiliaryType(reader, format, tag, type, ref value, true, false, false, false) &&
value != null)
{
if (!singleton)
{
#if FX11
result.Add(value);
#else
yield return value;
#endif
value = null; // fresh item each time
}
}
if (singleton && value != null)
{
#if FX11
result.Add(value);
#else
yield return value;
#endif
}
#if FX11
object[] resultArr = new object[result.Count];
result.CopyTo(resultArr, 0);
return resultArr;
#endif
}
finally
{
ProtoReader.Recycle(reader);
extn.EndQuery(stream);
}
#endif
}
internal static void AppendExtendValue(TypeModel model, IExtensible instance, int tag, DataFormat format,
object value)
{
#if FEAT_IKVM
throw new NotSupportedException();
#else
if (instance == null) throw new ArgumentNullException("instance");
if (value == null) throw new ArgumentNullException("value");
// TODO
//model.CheckTagNotInUse(tag);
// obtain the extension object and prepare to write
IExtension extn = instance.GetExtensionObject(true);
if (extn == null)
throw new InvalidOperationException("No extension object available; appended data would be lost.");
bool commit = false;
Stream stream = extn.BeginAppend();
try
{
using (ProtoWriter writer = new ProtoWriter(stream, model, null))
{
model.TrySerializeAuxiliaryType(writer, null, format, tag, value, false);
writer.Close();
}
commit = true;
}
finally
{
extn.EndAppend(stream, commit);
}
#endif
}
//#if !NO_GENERICS
// /// <summary>
// /// Stores the given value into the instance's stream; the serializer
// /// is inferred from TValue and format.
// /// </summary>
// /// <remarks>Needs to be public to be callable thru reflection in Silverlight</remarks>
// public static void AppendExtendValueTyped<TSource, TValue>(
// TypeModel model, TSource instance, int tag, DataFormat format, TValue value)
// where TSource : class, IExtensible
// {
// AppendExtendValue(model, instance, tag, format, value);
// }
//#endif
}
}

View File

@ -1,630 +0,0 @@
using System;
using System.Collections;
#if FEAT_IKVM
using Type = IKVM.Reflection.Type;
using IKVM.Reflection;
#else
using System.Reflection;
#endif
namespace ProtoBuf
{
/// <summary>
/// Not all frameworks are created equal (fx1.1 vs fx2.0,
/// micro-framework, compact-framework,
/// silverlight, etc). This class simply wraps up a few things that would
/// otherwise make the real code unnecessarily messy, providing fallback
/// implementations if necessary.
/// </summary>
internal sealed class Helpers
{
private Helpers()
{
}
public static System.Text.StringBuilder AppendLine(System.Text.StringBuilder builder)
{
#if CF2
return builder.Append("\r\n");
#elif FX11
return builder.Append(Environment.NewLine);
#else
return builder.AppendLine();
#endif
}
public static bool IsNullOrEmpty(string value)
{
// yes, FX11 lacks this!
return value == null || value.Length == 0;
}
[System.Diagnostics.Conditional("DEBUG")]
public static void DebugWriteLine(string message, object obj)
{
#if DEBUG
string suffix;
try
{
suffix = obj == null ? "(null)" : obj.ToString();
}
catch
{
suffix = "(exception)";
}
DebugWriteLine(message + ": " + suffix);
#endif
}
[System.Diagnostics.Conditional("DEBUG")]
public static void DebugWriteLine(string message)
{
#if DEBUG
#if MF
Microsoft.SPOT.Debug.Print(message);
#else
System.Diagnostics.Debug.WriteLine(message);
#endif
#endif
}
[System.Diagnostics.Conditional("TRACE")]
public static void TraceWriteLine(string message)
{
#if TRACE
#if MF
Microsoft.SPOT.Trace.Print(message);
#elif SILVERLIGHT || MONODROID || CF2 || WINRT || IOS || PORTABLE
System.Diagnostics.Debug.WriteLine(message);
#else
System.Diagnostics.Trace.WriteLine(message);
#endif
#endif
}
[System.Diagnostics.Conditional("DEBUG")]
public static void DebugAssert(bool condition, string message)
{
#if DEBUG
if (!condition)
{
#if MF
Microsoft.SPOT.Debug.Assert(false, message);
#else
System.Diagnostics.Debug.Assert(false, message);
}
#endif
#endif
}
[System.Diagnostics.Conditional("DEBUG")]
public static void DebugAssert(bool condition, string message, params object[] args)
{
#if DEBUG
if (!condition) DebugAssert(false, string.Format(message, args));
#endif
}
[System.Diagnostics.Conditional("DEBUG")]
public static void DebugAssert(bool condition)
{
#if DEBUG
#if MF
Microsoft.SPOT.Debug.Assert(condition);
#else
if (!condition && System.Diagnostics.Debugger.IsAttached) System.Diagnostics.Debugger.Break();
System.Diagnostics.Debug.Assert(condition);
#endif
#endif
}
#if !NO_RUNTIME
public static void Sort(int[] keys, object[] values)
{
// bubble-sort; it'll work on MF, has small code,
// and works well-enough for our sizes. This approach
// also allows us to do `int` compares without having
// to go via IComparable etc, so win:win
bool swapped;
do
{
swapped = false;
for (int i = 1; i < keys.Length; i++)
{
if (keys[i - 1] > keys[i])
{
int tmpKey = keys[i];
keys[i] = keys[i - 1];
keys[i - 1] = tmpKey;
object tmpValue = values[i];
values[i] = values[i - 1];
values[i - 1] = tmpValue;
swapped = true;
}
}
} while (swapped);
}
#endif
public static void BlockCopy(byte[] from, int fromIndex, byte[] to, int toIndex, int count)
{
#if MF || WINRT
Array.Copy(from, fromIndex, to, toIndex, count);
#else
Buffer.BlockCopy(from, fromIndex, to, toIndex, count);
#endif
}
public static bool IsInfinity(float value)
{
#if MF
const float inf = (float)1.0 / (float)0.0, minf = (float)-1.0F / (float)0.0;
return value == inf || value == minf;
#else
return float.IsInfinity(value);
#endif
}
#if WINRT
internal static MemberInfo GetInstanceMember(TypeInfo declaringType, string name)
{
PropertyInfo prop = declaringType.GetDeclaredProperty(name);
MethodInfo method;
if (prop != null && (method = Helpers.GetGetMethod(prop, true, true)) != null && !method.IsStatic) return prop;
FieldInfo field = declaringType.GetDeclaredField(name);
if (field != null && !field.IsStatic) return field;
return null;
}
internal static MethodInfo GetInstanceMethod(TypeInfo declaringType, string name)
{
foreach (MethodInfo method in declaringType.DeclaredMethods)
{
if (!method.IsStatic && method.Name == name)
{
return method;
}
}
return null;
}
internal static MethodInfo GetStaticMethod(TypeInfo declaringType, string name)
{
foreach (MethodInfo method in declaringType.DeclaredMethods)
{
if (method.IsStatic && method.Name == name)
{
return method;
}
}
return null;
}
internal static MethodInfo GetInstanceMethod(Type declaringType, string name, Type[] types)
{
return GetInstanceMethod(declaringType.GetTypeInfo(), name, types);
}
internal static MethodInfo GetInstanceMethod(TypeInfo declaringType, string name, Type[] types)
{
if (types == null) types = EmptyTypes;
foreach (MethodInfo method in declaringType.DeclaredMethods)
{
if (!method.IsStatic && method.Name == name)
{
if(IsMatch(method.GetParameters(), types)) return method;
}
}
return null;
}
#else
internal static MethodInfo GetInstanceMethod(Type declaringType, string name)
{
return declaringType.GetMethod(name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
}
internal static MethodInfo GetStaticMethod(Type declaringType, string name)
{
return declaringType.GetMethod(name, BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
}
internal static MethodInfo GetInstanceMethod(Type declaringType, string name, Type[] types)
{
if (types == null) types = EmptyTypes;
#if PORTABLE
MethodInfo method = declaringType.GetMethod(name, types);
if (method != null && method.IsStatic) method = null;
return method;
#else
return declaringType.GetMethod(name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic,
null, types, null);
#endif
}
#endif
internal static bool IsSubclassOf(Type type, Type baseClass)
{
#if WINRT
return type.GetTypeInfo().IsSubclassOf(baseClass);
#else
return type.IsSubclassOf(baseClass);
#endif
}
public static bool IsInfinity(double value)
{
#if MF
const double inf = (double)1.0 / (double)0.0, minf = (double)-1.0F / (double)0.0;
return value == inf || value == minf;
#else
return double.IsInfinity(value);
#endif
}
public static readonly Type[] EmptyTypes =
#if PORTABLE || WINRT || CF2 || CF35
new Type[0];
#else
Type.EmptyTypes;
#endif
#if WINRT
private static readonly Type[] knownTypes = new Type[] {
typeof(bool), typeof(char), typeof(sbyte), typeof(byte),
typeof(short), typeof(ushort), typeof(int), typeof(uint),
typeof(long), typeof(ulong), typeof(float), typeof(double),
typeof(decimal), typeof(string),
typeof(DateTime), typeof(TimeSpan), typeof(Guid), typeof(Uri),
typeof(byte[]), typeof(System.Type)};
private static readonly ProtoTypeCode[] knownCodes = new ProtoTypeCode[] {
ProtoTypeCode.Boolean, ProtoTypeCode.Char, ProtoTypeCode.SByte, ProtoTypeCode.Byte,
ProtoTypeCode.Int16, ProtoTypeCode.UInt16, ProtoTypeCode.Int32, ProtoTypeCode.UInt32,
ProtoTypeCode.Int64, ProtoTypeCode.UInt64, ProtoTypeCode.Single, ProtoTypeCode.Double,
ProtoTypeCode.Decimal, ProtoTypeCode.String,
ProtoTypeCode.DateTime, ProtoTypeCode.TimeSpan, ProtoTypeCode.Guid, ProtoTypeCode.Uri,
ProtoTypeCode.ByteArray, ProtoTypeCode.Type
};
#endif
#if FEAT_IKVM
public static ProtoTypeCode GetTypeCode(IKVM.Reflection.Type type)
{
TypeCode code = IKVM.Reflection.Type.GetTypeCode(type);
switch (code)
{
case TypeCode.Empty:
case TypeCode.Boolean:
case TypeCode.Char:
case TypeCode.SByte:
case TypeCode.Byte:
case TypeCode.Int16:
case TypeCode.UInt16:
case TypeCode.Int32:
case TypeCode.UInt32:
case TypeCode.Int64:
case TypeCode.UInt64:
case TypeCode.Single:
case TypeCode.Double:
case TypeCode.Decimal:
case TypeCode.DateTime:
case TypeCode.String:
return (ProtoTypeCode)code;
}
switch(type.FullName)
{
case "System.TimeSpan": return ProtoTypeCode.TimeSpan;
case "System.Guid": return ProtoTypeCode.Guid;
case "System.Uri": return ProtoTypeCode.Uri;
case "System.Byte[]": return ProtoTypeCode.ByteArray;
case "System.Type": return ProtoTypeCode.Type;
}
return ProtoTypeCode.Unknown;
}
#endif
public static ProtoTypeCode GetTypeCode(System.Type type)
{
#if WINRT
int idx = Array.IndexOf<Type>(knownTypes, type);
if (idx >= 0) return knownCodes[idx];
return type == null ? ProtoTypeCode.Empty : ProtoTypeCode.Unknown;
#else
TypeCode code = System.Type.GetTypeCode(type);
switch (code)
{
case TypeCode.Empty:
case TypeCode.Boolean:
case TypeCode.Char:
case TypeCode.SByte:
case TypeCode.Byte:
case TypeCode.Int16:
case TypeCode.UInt16:
case TypeCode.Int32:
case TypeCode.UInt32:
case TypeCode.Int64:
case TypeCode.UInt64:
case TypeCode.Single:
case TypeCode.Double:
case TypeCode.Decimal:
case TypeCode.DateTime:
case TypeCode.String:
return (ProtoTypeCode) code;
}
if (type == typeof (TimeSpan)) return ProtoTypeCode.TimeSpan;
if (type == typeof (Guid)) return ProtoTypeCode.Guid;
if (type == typeof (Uri)) return ProtoTypeCode.Uri;
if (type == typeof (byte[])) return ProtoTypeCode.ByteArray;
if (type == typeof (System.Type)) return ProtoTypeCode.Type;
return ProtoTypeCode.Unknown;
#endif
}
#if FEAT_IKVM
internal static IKVM.Reflection.Type GetUnderlyingType(IKVM.Reflection.Type type)
{
if (type.IsValueType && type.IsGenericType && type.GetGenericTypeDefinition().FullName == "System.Nullable`1")
{
return type.GetGenericArguments()[0];
}
return null;
}
#endif
internal static System.Type GetUnderlyingType(System.Type type)
{
#if NO_GENERICS
return null; // never a Nullable<T>, so always returns null
#else
return Nullable.GetUnderlyingType(type);
#endif
}
internal static bool IsValueType(Type type)
{
#if WINRT
return type.GetTypeInfo().IsValueType;
#else
return type.IsValueType;
#endif
}
internal static bool IsEnum(Type type)
{
#if WINRT
return type.GetTypeInfo().IsEnum;
#else
return type.IsEnum;
#endif
}
internal static MethodInfo GetGetMethod(PropertyInfo property, bool nonPublic, bool allowInternal)
{
if (property == null) return null;
#if WINRT
MethodInfo method = property.GetMethod;
if (!nonPublic && method != null && !method.IsPublic) method = null;
return method;
#else
MethodInfo method = property.GetGetMethod(nonPublic);
if (method == null && !nonPublic && allowInternal)
{
// could be "internal" or "protected internal"; look for a non-public, then back-check
method = property.GetGetMethod(true);
if (method == null && !(method.IsAssembly || method.IsFamilyOrAssembly))
{
method = null;
}
}
return method;
#endif
}
internal static MethodInfo GetSetMethod(PropertyInfo property, bool nonPublic, bool allowInternal)
{
if (property == null) return null;
#if WINRT
MethodInfo method = property.SetMethod;
if (!nonPublic && method != null && !method.IsPublic) method = null;
return method;
#else
MethodInfo method = property.GetSetMethod(nonPublic);
if (method == null && !nonPublic && allowInternal)
{
// could be "internal" or "protected internal"; look for a non-public, then back-check
method = property.GetGetMethod(true);
if (method == null && !(method.IsAssembly || method.IsFamilyOrAssembly))
{
method = null;
}
}
return method;
#endif
}
#if FEAT_IKVM
internal static bool IsMatch(IKVM.Reflection.ParameterInfo[] parameters, IKVM.Reflection.Type[] parameterTypes)
{
if (parameterTypes == null) parameterTypes = Helpers.EmptyTypes;
if (parameters.Length != parameterTypes.Length) return false;
for (int i = 0; i < parameters.Length; i++)
{
if (parameters[i].ParameterType != parameterTypes[i]) return false;
}
return true;
}
#endif
#if WINRT
private static bool IsMatch(ParameterInfo[] parameters, Type[] parameterTypes)
{
if (parameterTypes == null) parameterTypes = EmptyTypes;
if (parameters.Length != parameterTypes.Length) return false;
for (int i = 0; i < parameters.Length; i++)
{
if (parameters[i].ParameterType != parameterTypes[i]) return false;
}
return true;
}
internal static ConstructorInfo GetConstructor(TypeInfo type, Type[] parameterTypes, bool nonPublic)
{
foreach (ConstructorInfo ctor in type.DeclaredConstructors)
{
if (!nonPublic && !ctor.IsPublic) continue;
if (IsMatch(ctor.GetParameters(), parameterTypes)) return ctor;
}
return null;
}
internal static ConstructorInfo[] GetConstructors(TypeInfo typeInfo, bool nonPublic)
{
if (nonPublic) return System.Linq.Enumerable.ToArray(typeInfo.DeclaredConstructors);
return System.Linq.Enumerable.ToArray(
System.Linq.Enumerable.Where(typeInfo.DeclaredConstructors, x => x.IsPublic));
}
internal static PropertyInfo GetProperty(TypeInfo type, string name, bool nonPublic)
{
return type.GetDeclaredProperty(name);
}
#else
internal static ConstructorInfo GetConstructor(Type type, Type[] parameterTypes, bool nonPublic)
{
#if PORTABLE
// pretty sure this will only ever return public, but...
ConstructorInfo ctor = type.GetConstructor(parameterTypes);
return (ctor != null && (nonPublic || ctor.IsPublic)) ? ctor : null;
#else
return type.GetConstructor(
nonPublic
? BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic
: BindingFlags.Instance | BindingFlags.Public,
null, parameterTypes, null);
#endif
}
internal static ConstructorInfo[] GetConstructors(Type type, bool nonPublic)
{
return type.GetConstructors(
nonPublic
? BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic
: BindingFlags.Instance | BindingFlags.Public);
}
internal static PropertyInfo GetProperty(Type type, string name, bool nonPublic)
{
return type.GetProperty(name,
nonPublic
? BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic
: BindingFlags.Instance | BindingFlags.Public);
}
#endif
internal static object ParseEnum(Type type, string value)
{
#if FEAT_IKVM
FieldInfo[] fields = type.GetFields();
foreach (FieldInfo field in fields)
{
if (string.Equals(field.Name, value, StringComparison.OrdinalIgnoreCase)) return field.GetRawConstantValue();
}
throw new ArgumentException("Enum value could not be parsed: " + value + ", " + type.FullName);
#else
return Enum.Parse(type, value, true);
#endif
}
internal static MemberInfo[] GetInstanceFieldsAndProperties(Type type, bool publicOnly)
{
#if WINRT
System.Collections.Generic.List<MemberInfo> members = new System.Collections.Generic.List<MemberInfo>();
foreach(FieldInfo field in type.GetRuntimeFields())
{
if(field.IsStatic) continue;
if(field.IsPublic || !publicOnly) members.Add(field);
}
foreach(PropertyInfo prop in type.GetRuntimeProperties())
{
MethodInfo getter = Helpers.GetGetMethod(prop, true, true);
if(getter == null || getter.IsStatic) continue;
if(getter.IsPublic || !publicOnly) members.Add(prop);
}
return members.ToArray();
#else
BindingFlags flags = publicOnly
? BindingFlags.Public | BindingFlags.Instance
: BindingFlags.Public | BindingFlags.Instance | BindingFlags.NonPublic;
PropertyInfo[] props = type.GetProperties(flags);
FieldInfo[] fields = type.GetFields(flags);
MemberInfo[] members = new MemberInfo[fields.Length + props.Length];
props.CopyTo(members, 0);
fields.CopyTo(members, props.Length);
return members;
#endif
}
internal static Type GetMemberType(MemberInfo member)
{
#if WINRT || PORTABLE
PropertyInfo prop = member as PropertyInfo;
if (prop != null) return prop.PropertyType;
FieldInfo fld = member as FieldInfo;
return fld == null ? null : fld.FieldType;
#else
switch (member.MemberType)
{
case MemberTypes.Field:
return ((FieldInfo) member).FieldType;
case MemberTypes.Property:
return ((PropertyInfo) member).PropertyType;
default:
return null;
}
#endif
}
internal static bool IsAssignableFrom(Type target, Type type)
{
#if WINRT
return target.GetTypeInfo().IsAssignableFrom(type.GetTypeInfo());
#else
return target.IsAssignableFrom(type);
#endif
}
}
/// <summary>
/// Intended to be a direct map to regular TypeCode, but:
/// - with missing types
/// - existing on WinRT
/// </summary>
internal enum ProtoTypeCode
{
Empty = 0,
Unknown = 1, // maps to TypeCode.Object
Boolean = 3,
Char = 4,
SByte = 5,
Byte = 6,
Int16 = 7,
UInt16 = 8,
Int32 = 9,
UInt32 = 10,
Int64 = 11,
UInt64 = 12,
Single = 13,
Double = 14,
Decimal = 15,
DateTime = 16,
String = 18,
// additions
TimeSpan = 100,
ByteArray = 101,
Guid = 102,
Uri = 103,
Type = 104
}
}

View File

@ -1,22 +0,0 @@
namespace ProtoBuf
{
/// <summary>
/// Indicates that the implementing type has support for protocol-buffer
/// <see cref="IExtension">extensions</see>.
/// </summary>
/// <remarks>Can be implemented by deriving from Extensible.</remarks>
public interface IExtensible
{
/// <summary>
/// Retrieves the <see cref="IExtension">extension</see> object for the current
/// instance, optionally creating it if it does not already exist.
/// </summary>
/// <param name="createIfMissing">Should a new extension object be
/// created if it does not already exist?</param>
/// <returns>The extension object if it exists (or was created), or null
/// if the extension object does not exist or is not available.</returns>
/// <remarks>The <c>createIfMissing</c> argument is false during serialization,
/// and true during deserialization upon encountering unexpected fields.</remarks>
IExtension GetExtensionObject(bool createIfMissing);
}
}

View File

@ -1,47 +0,0 @@
using System.IO;
namespace ProtoBuf
{
/// <summary>
/// Provides addition capability for supporting unexpected fields during
/// protocol-buffer serialization/deserialization. This allows for loss-less
/// round-trip/merge, even when the data is not fully understood.
/// </summary>
public interface IExtension
{
/// <summary>
/// Requests a stream into which any unexpected fields can be persisted.
/// </summary>
/// <returns>A new stream suitable for storing data.</returns>
Stream BeginAppend();
/// <summary>
/// Indicates that all unexpected fields have now been stored. The
/// implementing class is responsible for closing the stream. If
/// "commit" is not true the data may be discarded.
/// </summary>
/// <param name="stream">The stream originally obtained by BeginAppend.</param>
/// <param name="commit">True if the append operation completed successfully.</param>
void EndAppend(Stream stream, bool commit);
/// <summary>
/// Requests a stream of the unexpected fields previously stored.
/// </summary>
/// <returns>A prepared stream of the unexpected fields.</returns>
Stream BeginQuery();
/// <summary>
/// Indicates that all unexpected fields have now been read. The
/// implementing class is responsible for closing the stream.
/// </summary>
/// <param name="stream">The stream originally obtained by BeginQuery.</param>
void EndQuery(Stream stream);
/// <summary>
/// Requests the length of the raw binary stream; this is used
/// when serializing sub-entities to indicate the expected size.
/// </summary>
/// <returns>The length of the binary stream representing unexpected data.</returns>
int GetLength();
}
}

View File

@ -1,33 +0,0 @@
using System;
namespace ProtoBuf
{
/// <summary>
/// Specifies the method used to infer field tags for members of the type
/// under consideration. Tags are deduced using the invariant alphabetic
/// sequence of the members' names; this makes implicit field tags very brittle,
/// and susceptible to changes such as field names (normally an isolated
/// change).
/// </summary>
public enum ImplicitFields
{
/// <summary>
/// No members are serialized implicitly; all members require a suitable
/// attribute such as [ProtoMember]. This is the recmomended mode for
/// most scenarios.
/// </summary>
None = 0,
/// <summary>
/// Public properties and fields are eligible for implicit serialization;
/// this treats the public API as a contract. Ordering beings from ImplicitFirstTag.
/// </summary>
AllPublic = 1,
/// <summary>
/// Public and non-public fields are eligible for implicit serialization;
/// this acts as a state/implementation serializer. Ordering beings from ImplicitFirstTag.
/// </summary>
AllFields = 2
}
}

View File

@ -1,47 +0,0 @@
//#if !NO_GENERICS
//using System.Collections.Generic;
//namespace ProtoBuf
//{
// /// <summary>
// /// Mutable version of the common key/value pair struct; used during serialization. This type is intended for internal use only and should not
// /// be used by calling code; it is required to be public for implementation reasons.
// /// </summary>
// [ProtoContract]
// public struct KeyValuePairSurrogate<TKey,TValue>
// {
// private TKey key;
// private TValue value;
// /// <summary>
// /// The key of the pair.
// /// </summary>
// [ProtoMember(1, IsRequired = true)]
// public TKey Key { get { return key; } set { key = value; } }
// /// <summary>
// /// The value of the pair.
// /// </summary>
// [ProtoMember(2)]
// public TValue Value{ get { return value; } set { this.value = value; } }
// private KeyValuePairSurrogate(TKey key, TValue value)
// {
// this.key = key;
// this.value = value;
// }
// /// <summary>
// /// Convert a surrogate instance to a standard pair instance.
// /// </summary>
// public static implicit operator KeyValuePair<TKey, TValue> (KeyValuePairSurrogate<TKey, TValue> value)
// {
// return new KeyValuePair<TKey,TValue>(value.key, value.value);
// }
// /// <summary>
// /// Convert a standard pair instance to a surrogate instance.
// /// </summary>
// public static implicit operator KeyValuePairSurrogate<TKey, TValue>(KeyValuePair<TKey, TValue> value)
// {
// return new KeyValuePairSurrogate<TKey, TValue>(value.Key, value.Value);
// }
// }
//}
//#endif

View File

@ -1,207 +0,0 @@
#if !NO_RUNTIME
using System;
#if FEAT_IKVM
using Type = IKVM.Reflection.Type;
using IKVM.Reflection;
#else
using System.Reflection;
#endif
namespace ProtoBuf.Meta
{
internal abstract class AttributeMap
{
#if DEBUG
[Obsolete("Please use AttributeType instead")]
public new Type GetType()
{
return AttributeType;
}
#endif
public abstract bool TryGet(string key, bool publicOnly, out object value);
public bool TryGet(string key, out object value)
{
return TryGet(key, true, out value);
}
public abstract Type AttributeType { get; }
public static AttributeMap[] Create(TypeModel model, Type type, bool inherit)
{
#if FEAT_IKVM
Type attribType = model.MapType(typeof(System.Attribute));
System.Collections.Generic.IList<CustomAttributeData> all = type.__GetCustomAttributes(attribType, inherit);
AttributeMap[] result = new AttributeMap[all.Count];
int index = 0;
foreach (CustomAttributeData attrib in all)
{
result[index++] = new AttributeDataMap(attrib);
}
return result;
#else
#if WINRT
Attribute[] all = System.Linq.Enumerable.ToArray(type.GetTypeInfo().GetCustomAttributes(inherit));
#else
object[] all = type.GetCustomAttributes(inherit);
#endif
AttributeMap[] result = new AttributeMap[all.Length];
for (int i = 0; i < all.Length; i++)
{
result[i] = new ReflectionAttributeMap((Attribute) all[i]);
}
return result;
#endif
}
public static AttributeMap[] Create(TypeModel model, MemberInfo member, bool inherit)
{
#if FEAT_IKVM
System.Collections.Generic.IList<CustomAttributeData> all = member.__GetCustomAttributes(model.MapType(typeof(Attribute)), inherit);
AttributeMap[] result = new AttributeMap[all.Count];
int index = 0;
foreach (CustomAttributeData attrib in all)
{
result[index++] = new AttributeDataMap(attrib);
}
return result;
#else
#if WINRT
Attribute[] all = System.Linq.Enumerable.ToArray(member.GetCustomAttributes(inherit));
#else
object[] all = member.GetCustomAttributes(inherit);
#endif
AttributeMap[] result = new AttributeMap[all.Length];
for (int i = 0; i < all.Length; i++)
{
result[i] = new ReflectionAttributeMap((Attribute) all[i]);
}
return result;
#endif
}
public static AttributeMap[] Create(TypeModel model, Assembly assembly)
{
#if FEAT_IKVM
const bool inherit = false;
System.Collections.Generic.IList<CustomAttributeData> all = assembly.__GetCustomAttributes(model.MapType(typeof(Attribute)), inherit);
AttributeMap[] result = new AttributeMap[all.Count];
int index = 0;
foreach (CustomAttributeData attrib in all)
{
result[index++] = new AttributeDataMap(attrib);
}
return result;
#else
#if WINRT
Attribute[] all = System.Linq.Enumerable.ToArray(assembly.GetCustomAttributes());
#else
const bool inherit = false;
object[] all = assembly.GetCustomAttributes(inherit);
#endif
AttributeMap[] result = new AttributeMap[all.Length];
for (int i = 0; i < all.Length; i++)
{
result[i] = new ReflectionAttributeMap((Attribute) all[i]);
}
return result;
#endif
}
#if FEAT_IKVM
private sealed class AttributeDataMap : AttributeMap
{
public override Type AttributeType
{
get { return attribute.Constructor.DeclaringType; }
}
private readonly CustomAttributeData attribute;
public AttributeDataMap(CustomAttributeData attribute)
{
this.attribute = attribute;
}
public override bool TryGet(string key, bool publicOnly, out object value)
{
foreach (CustomAttributeNamedArgument arg in attribute.NamedArguments)
{
if (string.Equals(arg.MemberInfo.Name, key, StringComparison.OrdinalIgnoreCase))
{
value = arg.TypedValue.Value;
return true;
}
}
int index = 0;
ParameterInfo[] parameters = attribute.Constructor.GetParameters();
foreach (CustomAttributeTypedArgument arg in attribute.ConstructorArguments)
{
if (string.Equals(parameters[index++].Name, key, StringComparison.OrdinalIgnoreCase))
{
value = arg.Value;
return true;
}
}
value = null;
return false;
}
}
#else
public abstract object Target { get; }
private sealed class ReflectionAttributeMap : AttributeMap
{
public override object Target
{
get { return attribute; }
}
public override Type AttributeType
{
get { return attribute.GetType(); }
}
public override bool TryGet(string key, bool publicOnly, out object value)
{
MemberInfo[] members = Helpers.GetInstanceFieldsAndProperties(attribute.GetType(), publicOnly);
foreach (MemberInfo member in members)
{
#if FX11
if (member.Name.ToUpper() == key.ToUpper())
#else
if (string.Equals(member.Name, key, StringComparison.OrdinalIgnoreCase))
#endif
{
PropertyInfo prop = member as PropertyInfo;
if (prop != null)
{
value = prop.GetValue(attribute, null);
return true;
}
FieldInfo field = member as FieldInfo;
if (field != null)
{
value = field.GetValue(attribute);
return true;
}
throw new NotSupportedException(member.GetType().Name);
}
}
value = null;
return false;
}
private readonly Attribute attribute;
public ReflectionAttributeMap(Attribute attribute)
{
this.attribute = attribute;
}
}
#endif
}
}
#endif

View File

@ -1,303 +0,0 @@
using System;
using System.Collections;
namespace ProtoBuf.Meta
{
internal sealed class MutableList : BasicList
{
/* Like BasicList, but allows existing values to be changed
*/
public new object this[int index]
{
get { return head[index]; }
set { head[index] = value; }
}
public void RemoveLast()
{
head.RemoveLastWithMutate();
}
public void Clear()
{
head.Clear();
}
}
internal class BasicList : IEnumerable
{
/* Requirements:
* - Fast access by index
* - Immutable in the tail, so a node can be read (iterated) without locking
* - Lock-free tail handling must match the memory mode; struct for Node
* wouldn't work as "read" would not be atomic
* - Only operation required is append, but this shouldn't go out of its
* way to be inefficient
* - Assume that the caller is handling thread-safety (to co-ordinate with
* other code); no attempt to be thread-safe
* - Assume that the data is private; internal data structure is allowed to
* be mutable (i.e. array is fine as long as we don't screw it up)
*/
private static readonly Node nil = new Node(null, 0);
public void CopyTo(Array array, int offset)
{
head.CopyTo(array, offset);
}
protected Node head = nil;
public int Add(object value)
{
return (head = head.Append(value)).Length - 1;
}
public object this[int index]
{
get { return head[index]; }
}
//public object TryGet(int index)
//{
// return head.TryGet(index);
//}
public void Trim()
{
head = head.Trim();
}
public int Count
{
get { return head.Length; }
}
IEnumerator IEnumerable.GetEnumerator()
{
return new NodeEnumerator(head);
}
public NodeEnumerator GetEnumerator()
{
return new NodeEnumerator(head);
}
public struct NodeEnumerator : IEnumerator
{
private int position;
private readonly Node node;
internal NodeEnumerator(Node node)
{
this.position = -1;
this.node = node;
}
void IEnumerator.Reset()
{
position = -1;
}
public object Current
{
get { return node[position]; }
}
public bool MoveNext()
{
int len = node.Length;
return (position <= len) && (++position < len);
}
}
internal sealed class Node
{
public object this[int index]
{
get
{
if (index >= 0 && index < length)
{
return data[index];
}
throw new ArgumentOutOfRangeException("index");
}
set
{
if (index >= 0 && index < length)
{
data[index] = value;
}
else
{
throw new ArgumentOutOfRangeException("index");
}
}
}
//public object TryGet(int index)
//{
// return (index >= 0 && index < length) ? data[index] : null;
//}
private readonly object[] data;
private int length;
public int Length
{
get { return length; }
}
internal Node(object[] data, int length)
{
Helpers.DebugAssert((data == null && length == 0) ||
(data != null && length > 0 && length <= data.Length));
this.data = data;
this.length = length;
}
public void RemoveLastWithMutate()
{
if (length == 0) throw new InvalidOperationException();
length -= 1;
}
public Node Append(object value)
{
object[] newData;
int newLength = length + 1;
if (data == null)
{
newData = new object[10];
}
else if (length == data.Length)
{
newData = new object[data.Length*2];
Array.Copy(data, newData, length);
}
else
{
newData = data;
}
newData[length] = value;
return new Node(newData, newLength);
}
public Node Trim()
{
if (length == 0 || length == data.Length) return this;
object[] newData = new object[length];
Array.Copy(data, newData, length);
return new Node(newData, length);
}
internal int IndexOfString(string value)
{
for (int i = 0; i < length; i++)
{
if ((string) value == (string) data[i]) return i;
}
return -1;
}
internal int IndexOfReference(object instance)
{
for (int i = 0; i < length; i++)
{
if ((object) instance == (object) data[i]) return i;
} // ^^^ (object) above should be preserved, even if this was typed; needs
// to be a reference check
return -1;
}
internal int IndexOf(MatchPredicate predicate, object ctx)
{
for (int i = 0; i < length; i++)
{
if (predicate(data[i], ctx)) return i;
}
return -1;
}
internal void CopyTo(Array array, int offset)
{
if (length > 0)
{
Array.Copy(data, 0, array, offset, length);
}
}
internal void Clear()
{
if (data != null)
{
Array.Clear(data, 0, data.Length);
}
length = 0;
}
}
internal int IndexOf(MatchPredicate predicate, object ctx)
{
return head.IndexOf(predicate, ctx);
}
internal int IndexOfString(string value)
{
return head.IndexOfString(value);
}
internal int IndexOfReference(object instance)
{
return head.IndexOfReference(instance);
}
internal delegate bool MatchPredicate(object value, object ctx);
internal bool Contains(object value)
{
foreach (object obj in this)
{
if (object.Equals(obj, value)) return true;
}
return false;
}
internal sealed class Group
{
public readonly int First;
public readonly BasicList Items;
public Group(int first)
{
this.First = first;
this.Items = new BasicList();
}
}
internal static BasicList GetContiguousGroups(int[] keys, object[] values)
{
if (keys == null) throw new ArgumentNullException("keys");
if (values == null) throw new ArgumentNullException("values");
if (values.Length < keys.Length)
throw new ArgumentException("Not all keys are covered by values", "values");
BasicList outer = new BasicList();
Group group = null;
for (int i = 0; i < keys.Length; i++)
{
if (i == 0 || keys[i] != keys[i - 1])
{
group = null;
}
if (group == null)
{
group = new Group(keys[i]);
outer.Add(group);
}
group.Items.Add(values[i]);
}
return outer;
}
}
}

View File

@ -1,131 +0,0 @@
#if !NO_RUNTIME
using System;
#if FEAT_IKVM
using Type = IKVM.Reflection.Type;
using IKVM.Reflection;
#else
using System.Reflection;
#endif
namespace ProtoBuf.Meta
{
/// <summary>
/// Represents the set of serialization callbacks to be used when serializing/deserializing a type.
/// </summary>
public class CallbackSet
{
private readonly MetaType metaType;
internal CallbackSet(MetaType metaType)
{
if (metaType == null) throw new ArgumentNullException("metaType");
this.metaType = metaType;
}
internal MethodInfo this[TypeModel.CallbackType callbackType]
{
get
{
switch (callbackType)
{
case TypeModel.CallbackType.BeforeSerialize:
return beforeSerialize;
case TypeModel.CallbackType.AfterSerialize:
return afterSerialize;
case TypeModel.CallbackType.BeforeDeserialize:
return beforeDeserialize;
case TypeModel.CallbackType.AfterDeserialize:
return afterDeserialize;
default:
throw new ArgumentException("Callback type not supported: " + callbackType.ToString(),
"callbackType");
}
}
}
internal static bool CheckCallbackParameters(TypeModel model, MethodInfo method)
{
ParameterInfo[] args = method.GetParameters();
for (int i = 0; i < args.Length; i++)
{
Type paramType = args[i].ParameterType;
if (paramType == model.MapType(typeof (SerializationContext)))
{
}
else if (paramType == model.MapType(typeof (System.Type)))
{
}
#if PLAT_BINARYFORMATTER
else if(paramType == model.MapType(typeof(System.Runtime.Serialization.StreamingContext))) {}
#endif
else return false;
}
return true;
}
private MethodInfo SanityCheckCallback(TypeModel model, MethodInfo callback)
{
metaType.ThrowIfFrozen();
if (callback == null) return callback; // fine
if (callback.IsStatic) throw new ArgumentException("Callbacks cannot be static", "callback");
if (callback.ReturnType != model.MapType(typeof (void))
|| !CheckCallbackParameters(model, callback))
{
throw CreateInvalidCallbackSignature(callback);
}
return callback;
}
internal static Exception CreateInvalidCallbackSignature(MethodInfo method)
{
return
new NotSupportedException("Invalid callback signature in " + method.DeclaringType.FullName + "." +
method.Name);
}
private MethodInfo beforeSerialize, afterSerialize, beforeDeserialize, afterDeserialize;
/// <summary>Called before serializing an instance</summary>
public MethodInfo BeforeSerialize
{
get { return beforeSerialize; }
set { beforeSerialize = SanityCheckCallback(metaType.Model, value); }
}
/// <summary>Called before deserializing an instance</summary>
public MethodInfo BeforeDeserialize
{
get { return beforeDeserialize; }
set { beforeDeserialize = SanityCheckCallback(metaType.Model, value); }
}
/// <summary>Called after serializing an instance</summary>
public MethodInfo AfterSerialize
{
get { return afterSerialize; }
set { afterSerialize = SanityCheckCallback(metaType.Model, value); }
}
/// <summary>Called after deserializing an instance</summary>
public MethodInfo AfterDeserialize
{
get { return afterDeserialize; }
set { afterDeserialize = SanityCheckCallback(metaType.Model, value); }
}
/// <summary>
/// True if any callback is set, else False
/// </summary>
public bool NonTrivial
{
get
{
return beforeSerialize != null || beforeDeserialize != null
|| afterSerialize != null || afterDeserialize != null;
}
}
}
}
#endif

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -1,97 +0,0 @@
#if !NO_RUNTIME
using System;
using ProtoBuf.Serializers;
namespace ProtoBuf.Meta
{
/// <summary>
/// Represents an inherited type in a type hierarchy.
/// </summary>
public sealed class SubType
{
internal sealed class Comparer : System.Collections.IComparer
#if !NO_GENERICS
, System.Collections.Generic.IComparer<SubType>
#endif
{
public static readonly Comparer Default = new Comparer();
public int Compare(object x, object y)
{
return Compare(x as SubType, y as SubType);
}
public int Compare(SubType x, SubType y)
{
if (ReferenceEquals(x, y)) return 0;
if (x == null) return -1;
if (y == null) return 1;
return x.FieldNumber.CompareTo(y.FieldNumber);
}
}
private readonly int fieldNumber;
/// <summary>
/// The field-number that is used to encapsulate the data (as a nested
/// message) for the derived dype.
/// </summary>
public int FieldNumber
{
get { return fieldNumber; }
}
/// <summary>
/// The sub-type to be considered.
/// </summary>
public MetaType DerivedType
{
get { return derivedType; }
}
private readonly MetaType derivedType;
/// <summary>
/// Creates a new SubType instance.
/// </summary>
/// <param name="fieldNumber">The field-number that is used to encapsulate the data (as a nested
/// message) for the derived dype.</param>
/// <param name="derivedType">The sub-type to be considered.</param>
/// <param name="format">Specific encoding style to use; in particular, Grouped can be used to avoid buffering, but is not the default.</param>
public SubType(int fieldNumber, MetaType derivedType, DataFormat format)
{
if (derivedType == null) throw new ArgumentNullException("derivedType");
if (fieldNumber <= 0) throw new ArgumentOutOfRangeException("fieldNumber");
this.fieldNumber = fieldNumber;
this.derivedType = derivedType;
this.dataFormat = format;
}
private readonly DataFormat dataFormat;
private IProtoSerializer serializer;
internal IProtoSerializer Serializer
{
get
{
if (serializer == null) serializer = BuildSerializer();
return serializer;
}
}
private IProtoSerializer BuildSerializer()
{
// note the caller here is MetaType.BuildSerializer, which already has the sync-lock
WireType wireType = WireType.String;
if (dataFormat == DataFormat.Group) wireType = WireType.StartGroup; // only one exception
IProtoSerializer ser = new SubItemSerializer(derivedType.Type, derivedType.GetKey(false, false), derivedType,
false);
return new TagDecorator(fieldNumber, wireType, false, ser);
}
}
}
#endif

View File

@ -1,67 +0,0 @@
using System;
namespace ProtoBuf.Meta
{
/// <summary>
/// Event arguments needed to perform type-formatting functions; this could be resolving a Type to a string suitable for serialization, or could
/// be requesting a Type from a string. If no changes are made, a default implementation will be used (from the assembly-qualified names).
/// </summary>
public class TypeFormatEventArgs : EventArgs
{
private Type type;
private string formattedName;
private readonly bool typeFixed;
/// <summary>
/// The type involved in this map; if this is initially null, a Type is expected to be provided for the string in FormattedName.
/// </summary>
public Type Type
{
get { return type; }
set
{
if (type != value)
{
if (typeFixed) throw new InvalidOperationException("The type is fixed and cannot be changed");
type = value;
}
}
}
/// <summary>
/// The formatted-name involved in this map; if this is initially null, a formatted-name is expected from the type in Type.
/// </summary>
public string FormattedName
{
get { return formattedName; }
set
{
if (formattedName != value)
{
if (!typeFixed)
throw new InvalidOperationException("The formatted-name is fixed and cannot be changed");
formattedName = value;
}
}
}
internal TypeFormatEventArgs(string formattedName)
{
if (Helpers.IsNullOrEmpty(formattedName)) throw new ArgumentNullException("formattedName");
this.formattedName = formattedName;
// typeFixed = false; <== implicit
}
internal TypeFormatEventArgs(System.Type type)
{
if (type == null) throw new ArgumentNullException("type");
this.type = type;
typeFixed = true;
}
}
/// <summary>
/// Delegate type used to perform type-formatting functions; the sender originates as the type-model.
/// </summary>
public delegate void TypeFormatEventHandler(object sender, TypeFormatEventArgs args);
}

File diff suppressed because it is too large Load Diff

View File

@ -1,734 +0,0 @@
#if !NO_RUNTIME
using System;
using ProtoBuf.Serializers;
using System.Globalization;
#if FEAT_IKVM
using Type = IKVM.Reflection.Type;
using IKVM.Reflection;
#else
using System.Reflection;
#endif
namespace ProtoBuf.Meta
{
/// <summary>
/// Represents a member (property/field) that is mapped to a protobuf field
/// </summary>
public class ValueMember
{
private readonly int fieldNumber;
/// <summary>
/// The number that identifies this member in a protobuf stream
/// </summary>
public int FieldNumber
{
get { return fieldNumber; }
}
private readonly MemberInfo member;
/// <summary>
/// Gets the member (field/property) which this member relates to.
/// </summary>
public MemberInfo Member
{
get { return member; }
}
private readonly Type parentType, itemType, defaultType, memberType;
private object defaultValue;
/// <summary>
/// Within a list / array / etc, the type of object for each item in the list (especially useful with ArrayList)
/// </summary>
public Type ItemType
{
get { return itemType; }
}
/// <summary>
/// The underlying type of the member
/// </summary>
public Type MemberType
{
get { return memberType; }
}
/// <summary>
/// For abstract types (IList etc), the type of concrete object to create (if required)
/// </summary>
public Type DefaultType
{
get { return defaultType; }
}
/// <summary>
/// The type the defines the member
/// </summary>
public Type ParentType
{
get { return parentType; }
}
/// <summary>
/// The default value of the item (members with this value will not be serialized)
/// </summary>
public object DefaultValue
{
get { return defaultValue; }
set
{
ThrowIfFrozen();
defaultValue = value;
}
}
private readonly RuntimeTypeModel model;
/// <summary>
/// Creates a new ValueMember instance
/// </summary>
public ValueMember(RuntimeTypeModel model, Type parentType, int fieldNumber, MemberInfo member, Type memberType,
Type itemType, Type defaultType, DataFormat dataFormat, object defaultValue)
: this(model, fieldNumber, memberType, itemType, defaultType, dataFormat)
{
if (member == null) throw new ArgumentNullException("member");
if (parentType == null) throw new ArgumentNullException("parentType");
if (fieldNumber < 1 && !Helpers.IsEnum(parentType)) throw new ArgumentOutOfRangeException("fieldNumber");
this.member = member;
this.parentType = parentType;
if (fieldNumber < 1 && !Helpers.IsEnum(parentType)) throw new ArgumentOutOfRangeException("fieldNumber");
//#if WINRT
if (defaultValue != null && model.MapType(defaultValue.GetType()) != memberType)
//#else
// if (defaultValue != null && !memberType.IsInstanceOfType(defaultValue))
//#endif
{
defaultValue = ParseDefaultValue(memberType, defaultValue);
}
this.defaultValue = defaultValue;
MetaType type = model.FindWithoutAdd(memberType);
if (type != null)
{
this.asReference = type.AsReferenceDefault;
}
else
{
// we need to scan the hard way; can't risk recursion by fully walking it
this.asReference = MetaType.GetAsReferenceDefault(model, memberType);
}
}
/// <summary>
/// Creates a new ValueMember instance
/// </summary>
internal ValueMember(RuntimeTypeModel model, int fieldNumber, Type memberType, Type itemType, Type defaultType,
DataFormat dataFormat)
{
if (memberType == null) throw new ArgumentNullException("memberType");
if (model == null) throw new ArgumentNullException("model");
this.fieldNumber = fieldNumber;
this.memberType = memberType;
this.itemType = itemType;
this.defaultType = defaultType;
this.model = model;
this.dataFormat = dataFormat;
}
internal object GetRawEnumValue()
{
#if WINRT || PORTABLE || CF || FX11
object value = ((FieldInfo)member).GetValue(null);
switch(Helpers.GetTypeCode(Enum.GetUnderlyingType(((FieldInfo)member).FieldType)))
{
case ProtoTypeCode.SByte: return (sbyte)value;
case ProtoTypeCode.Byte: return (byte)value;
case ProtoTypeCode.Int16: return (short)value;
case ProtoTypeCode.UInt16: return (ushort)value;
case ProtoTypeCode.Int32: return (int)value;
case ProtoTypeCode.UInt32: return (uint)value;
case ProtoTypeCode.Int64: return (long)value;
case ProtoTypeCode.UInt64: return (ulong)value;
default:
throw new InvalidOperationException();
}
#else
return ((FieldInfo) member).GetRawConstantValue();
#endif
}
private static object ParseDefaultValue(Type type, object value)
{
Type tmp = Helpers.GetUnderlyingType(type);
if (tmp != null) type = tmp;
if (value is string)
{
string s = (string) value;
if (Helpers.IsEnum(type)) return Helpers.ParseEnum(type, s);
switch (Helpers.GetTypeCode(type))
{
case ProtoTypeCode.Boolean:
return bool.Parse(s);
case ProtoTypeCode.Byte:
return byte.Parse(s, NumberStyles.Integer, CultureInfo.InvariantCulture);
case ProtoTypeCode.Char: // char.Parse missing on CF/phone7
if (s.Length == 1) return s[0];
throw new FormatException("Single character expected: \"" + s + "\"");
case ProtoTypeCode.DateTime:
return DateTime.Parse(s, CultureInfo.InvariantCulture);
case ProtoTypeCode.Decimal:
return decimal.Parse(s, NumberStyles.Any, CultureInfo.InvariantCulture);
case ProtoTypeCode.Double:
return double.Parse(s, NumberStyles.Any, CultureInfo.InvariantCulture);
case ProtoTypeCode.Int16:
return short.Parse(s, NumberStyles.Any, CultureInfo.InvariantCulture);
case ProtoTypeCode.Int32:
return int.Parse(s, NumberStyles.Any, CultureInfo.InvariantCulture);
case ProtoTypeCode.Int64:
return long.Parse(s, NumberStyles.Any, CultureInfo.InvariantCulture);
case ProtoTypeCode.SByte:
return sbyte.Parse(s, NumberStyles.Integer, CultureInfo.InvariantCulture);
case ProtoTypeCode.Single:
return float.Parse(s, NumberStyles.Any, CultureInfo.InvariantCulture);
case ProtoTypeCode.String:
return s;
case ProtoTypeCode.UInt16:
return ushort.Parse(s, NumberStyles.Any, CultureInfo.InvariantCulture);
case ProtoTypeCode.UInt32:
return uint.Parse(s, NumberStyles.Any, CultureInfo.InvariantCulture);
case ProtoTypeCode.UInt64:
return ulong.Parse(s, NumberStyles.Any, CultureInfo.InvariantCulture);
case ProtoTypeCode.TimeSpan:
return TimeSpan.Parse(s);
case ProtoTypeCode.Uri:
return s; // Uri is decorated as string
case ProtoTypeCode.Guid:
return new Guid(s);
}
}
#if FEAT_IKVM
if (Helpers.IsEnum(type)) return value; // return the underlying type instead
System.Type convertType = null;
switch(Helpers.GetTypeCode(type))
{
case ProtoTypeCode.SByte: convertType = typeof(sbyte); break;
case ProtoTypeCode.Int16: convertType = typeof(short); break;
case ProtoTypeCode.Int32: convertType = typeof(int); break;
case ProtoTypeCode.Int64: convertType = typeof(long); break;
case ProtoTypeCode.Byte: convertType = typeof(byte); break;
case ProtoTypeCode.UInt16: convertType = typeof(ushort); break;
case ProtoTypeCode.UInt32: convertType = typeof(uint); break;
case ProtoTypeCode.UInt64: convertType = typeof(ulong); break;
case ProtoTypeCode.Single: convertType = typeof(float); break;
case ProtoTypeCode.Double: convertType = typeof(double); break;
case ProtoTypeCode.Decimal: convertType = typeof(decimal); break;
}
if(convertType != null) return Convert.ChangeType(value, convertType, CultureInfo.InvariantCulture);
throw new ArgumentException("Unable to process default value: " + value + ", " + type.FullName);
#else
if (Helpers.IsEnum(type)) return Enum.ToObject(type, value);
return Convert.ChangeType(value, type, CultureInfo.InvariantCulture);
#endif
}
private IProtoSerializer serializer;
internal IProtoSerializer Serializer
{
get
{
if (serializer == null) serializer = BuildSerializer();
return serializer;
}
}
private DataFormat dataFormat;
/// <summary>
/// Specifies the rules used to process the field; this is used to determine the most appropriate
/// wite-type, but also to describe subtypes <i>within</i> that wire-type (such as SignedVariant)
/// </summary>
public DataFormat DataFormat
{
get { return dataFormat; }
set
{
ThrowIfFrozen();
this.dataFormat = value;
}
}
/// <summary>
/// Indicates whether this field should follow strict encoding rules; this means (for example) that if a "fixed32"
/// is encountered when "variant" is defined, then it will fail (throw an exception) when parsing. Note that
/// when serializing the defined type is always used.
/// </summary>
public bool IsStrict
{
get { return HasFlag(OPTIONS_IsStrict); }
set { SetFlag(OPTIONS_IsStrict, value, true); }
}
/// <summary>
/// Indicates whether this field should use packed encoding (which can save lots of space for repeated primitive values).
/// This option only applies to list/array data of primitive types (int, double, etc).
/// </summary>
public bool IsPacked
{
get { return HasFlag(OPTIONS_IsPacked); }
set { SetFlag(OPTIONS_IsPacked, value, true); }
}
/// <summary>
/// Indicates whether this field should *repace* existing values (the default is false, meaning *append*).
/// This option only applies to list/array data.
/// </summary>
public bool OverwriteList
{
get { return HasFlag(OPTIONS_OverwriteList); }
set { SetFlag(OPTIONS_OverwriteList, value, true); }
}
/// <summary>
/// Indicates whether this field is mandatory.
/// </summary>
public bool IsRequired
{
get { return HasFlag(OPTIONS_IsRequired); }
set { SetFlag(OPTIONS_IsRequired, value, true); }
}
private bool asReference;
/// <summary>
/// Enables full object-tracking/full-graph support.
/// </summary>
public bool AsReference
{
get { return asReference; }
set
{
ThrowIfFrozen();
asReference = value;
}
}
private bool dynamicType;
/// <summary>
/// Embeds the type information into the stream, allowing usage with types not known in advance.
/// </summary>
public bool DynamicType
{
get { return dynamicType; }
set
{
ThrowIfFrozen();
dynamicType = value;
}
}
private MethodInfo getSpecified, setSpecified;
/// <summary>
/// Specifies methods for working with optional data members.
/// </summary>
/// <param name="getSpecified">Provides a method (null for none) to query whether this member should
/// be serialized; it must be of the form "bool {Method}()". The member is only serialized if the
/// method returns true.</param>
/// <param name="setSpecified">Provides a method (null for none) to indicate that a member was
/// deserialized; it must be of the form "void {Method}(bool)", and will be called with "true"
/// when data is found.</param>
public void SetSpecified(MethodInfo getSpecified, MethodInfo setSpecified)
{
if (getSpecified != null)
{
if (getSpecified.ReturnType != model.MapType(typeof (bool))
|| getSpecified.IsStatic
|| getSpecified.GetParameters().Length != 0)
{
throw new ArgumentException("Invalid pattern for checking member-specified", "getSpecified");
}
}
if (setSpecified != null)
{
ParameterInfo[] args;
if (setSpecified.ReturnType != model.MapType(typeof (void))
|| setSpecified.IsStatic
|| (args = setSpecified.GetParameters()).Length != 1
|| args[0].ParameterType != model.MapType(typeof (bool)))
{
throw new ArgumentException("Invalid pattern for setting member-specified", "setSpecified");
}
}
ThrowIfFrozen();
this.getSpecified = getSpecified;
this.setSpecified = setSpecified;
}
private void ThrowIfFrozen()
{
if (serializer != null)
throw new InvalidOperationException("The type cannot be changed once a serializer has been generated");
}
private IProtoSerializer BuildSerializer()
{
int opaqueToken = 0;
try
{
model.TakeLock(ref opaqueToken); // check nobody is still adding this type
WireType wireType;
Type finalType = itemType == null ? memberType : itemType;
IProtoSerializer ser = TryGetCoreSerializer(model, dataFormat, finalType, out wireType, asReference,
dynamicType, OverwriteList, true);
if (ser == null)
{
throw new InvalidOperationException("No serializer defined for type: " + finalType.FullName);
}
// apply tags
if (itemType != null && SupportNull)
{
if (IsPacked)
{
throw new NotSupportedException("Packed encodings cannot support null values");
}
ser = new TagDecorator(NullDecorator.Tag, wireType, IsStrict, ser);
ser = new NullDecorator(model, ser);
ser = new TagDecorator(fieldNumber, WireType.StartGroup, false, ser);
}
else
{
ser = new TagDecorator(fieldNumber, wireType, IsStrict, ser);
}
// apply lists if appropriate
if (itemType != null)
{
#if NO_GENERICS
Type underlyingItemType = itemType;
#else
Type underlyingItemType = SupportNull ? itemType : Helpers.GetUnderlyingType(itemType) ?? itemType;
#endif
Helpers.DebugAssert(underlyingItemType == ser.ExpectedType,
"Wrong type in the tail; expected {0}, received {1}", ser.ExpectedType, underlyingItemType);
if (memberType.IsArray)
{
ser = new ArrayDecorator(model, ser, fieldNumber, IsPacked, wireType, memberType, OverwriteList,
SupportNull);
}
else
{
ser = ListDecorator.Create(model, memberType, defaultType, ser, fieldNumber, IsPacked, wireType,
member != null && PropertyDecorator.CanWrite(model, member), OverwriteList, SupportNull);
}
}
else if (defaultValue != null && !IsRequired && getSpecified == null)
{
// note: "ShouldSerialize*" / "*Specified" / etc ^^^^ take precedence over defaultValue,
// as does "IsRequired"
ser = new DefaultValueDecorator(model, defaultValue, ser);
}
if (memberType == model.MapType(typeof (Uri)))
{
ser = new UriDecorator(model, ser);
}
if (member != null)
{
PropertyInfo prop = member as PropertyInfo;
if (prop != null)
{
ser = new PropertyDecorator(model, parentType, (PropertyInfo) member, ser);
}
else
{
FieldInfo fld = member as FieldInfo;
if (fld != null)
{
ser = new FieldDecorator(parentType, (FieldInfo) member, ser);
}
else
{
throw new InvalidOperationException();
}
}
if (getSpecified != null || setSpecified != null)
{
ser = new MemberSpecifiedDecorator(getSpecified, setSpecified, ser);
}
}
return ser;
}
finally
{
model.ReleaseLock(opaqueToken);
}
}
private static WireType GetIntWireType(DataFormat format, int width)
{
switch (format)
{
case DataFormat.ZigZag:
return WireType.SignedVariant;
case DataFormat.FixedSize:
return width == 32 ? WireType.Fixed32 : WireType.Fixed64;
case DataFormat.TwosComplement:
case DataFormat.Default:
return WireType.Variant;
default:
throw new InvalidOperationException();
}
}
private static WireType GetDateTimeWireType(DataFormat format)
{
switch (format)
{
case DataFormat.Group:
return WireType.StartGroup;
case DataFormat.FixedSize:
return WireType.Fixed64;
case DataFormat.Default:
return WireType.String;
default:
throw new InvalidOperationException();
}
}
internal static IProtoSerializer TryGetCoreSerializer(RuntimeTypeModel model, DataFormat dataFormat, Type type,
out WireType defaultWireType,
bool asReference, bool dynamicType, bool overwriteList, bool allowComplexTypes)
{
#if !NO_GENERICS
{
Type tmp = Helpers.GetUnderlyingType(type);
if (tmp != null) type = tmp;
}
#endif
if (Helpers.IsEnum(type))
{
if (allowComplexTypes && model != null)
{
// need to do this before checking the typecode; an int enum will report Int32 etc
defaultWireType = WireType.Variant;
return new EnumSerializer(type, model.GetEnumMap(type));
}
else
{
// enum is fine for adding as a meta-type
defaultWireType = WireType.None;
return null;
}
}
ProtoTypeCode code = Helpers.GetTypeCode(type);
switch (code)
{
case ProtoTypeCode.Int32:
defaultWireType = GetIntWireType(dataFormat, 32);
return new Int32Serializer(model);
case ProtoTypeCode.UInt32:
defaultWireType = GetIntWireType(dataFormat, 32);
return new UInt32Serializer(model);
case ProtoTypeCode.Int64:
defaultWireType = GetIntWireType(dataFormat, 64);
return new Int64Serializer(model);
case ProtoTypeCode.UInt64:
defaultWireType = GetIntWireType(dataFormat, 64);
return new UInt64Serializer(model);
case ProtoTypeCode.String:
defaultWireType = WireType.String;
if (asReference)
{
return new NetObjectSerializer(model, model.MapType(typeof (string)), 0,
BclHelpers.NetObjectOptions.AsReference);
}
return new StringSerializer(model);
case ProtoTypeCode.Single:
defaultWireType = WireType.Fixed32;
return new SingleSerializer(model);
case ProtoTypeCode.Double:
defaultWireType = WireType.Fixed64;
return new DoubleSerializer(model);
case ProtoTypeCode.Boolean:
defaultWireType = WireType.Variant;
return new BooleanSerializer(model);
case ProtoTypeCode.DateTime:
defaultWireType = GetDateTimeWireType(dataFormat);
return new DateTimeSerializer(model);
case ProtoTypeCode.Decimal:
defaultWireType = WireType.String;
return new DecimalSerializer(model);
case ProtoTypeCode.Byte:
defaultWireType = GetIntWireType(dataFormat, 32);
return new ByteSerializer(model);
case ProtoTypeCode.SByte:
defaultWireType = GetIntWireType(dataFormat, 32);
return new SByteSerializer(model);
case ProtoTypeCode.Char:
defaultWireType = WireType.Variant;
return new CharSerializer(model);
case ProtoTypeCode.Int16:
defaultWireType = GetIntWireType(dataFormat, 32);
return new Int16Serializer(model);
case ProtoTypeCode.UInt16:
defaultWireType = GetIntWireType(dataFormat, 32);
return new UInt16Serializer(model);
case ProtoTypeCode.TimeSpan:
defaultWireType = GetDateTimeWireType(dataFormat);
return new TimeSpanSerializer(model);
case ProtoTypeCode.Guid:
defaultWireType = WireType.String;
return new GuidSerializer(model);
case ProtoTypeCode.Uri:
defaultWireType = WireType.String;
return new StringSerializer(model); // treat as string; wrapped in decorator later
case ProtoTypeCode.ByteArray:
defaultWireType = WireType.String;
return new BlobSerializer(model, overwriteList);
case ProtoTypeCode.Type:
defaultWireType = WireType.String;
return new SystemTypeSerializer(model);
}
IProtoSerializer parseable = model.AllowParseableTypes ? ParseableSerializer.TryCreate(type, model) : null;
if (parseable != null)
{
defaultWireType = WireType.String;
return parseable;
}
if (allowComplexTypes && model != null)
{
int key = model.GetKey(type, false, true);
if (asReference || dynamicType)
{
defaultWireType = dataFormat == DataFormat.Group ? WireType.StartGroup : WireType.String;
BclHelpers.NetObjectOptions options = BclHelpers.NetObjectOptions.None;
if (asReference) options |= BclHelpers.NetObjectOptions.AsReference;
if (dynamicType) options |= BclHelpers.NetObjectOptions.DynamicType;
if (key >= 0)
{
// exists
if (asReference && Helpers.IsValueType(type))
{
string message = "AsReference cannot be used with value-types";
if (type.Name == "KeyValuePair`2")
{
message += "; please see http://stackoverflow.com/q/14436606/";
}
else
{
message += ": " + type.FullName;
}
throw new InvalidOperationException(message);
}
MetaType meta = model[type];
if (asReference && meta.IsAutoTuple) options |= BclHelpers.NetObjectOptions.LateSet;
if (meta.UseConstructor) options |= BclHelpers.NetObjectOptions.UseConstructor;
}
return new NetObjectSerializer(model, type, key, options);
}
if (key >= 0)
{
defaultWireType = dataFormat == DataFormat.Group ? WireType.StartGroup : WireType.String;
return new SubItemSerializer(type, key, model[type], true);
}
}
defaultWireType = WireType.None;
return null;
}
private string name;
internal void SetName(string name)
{
ThrowIfFrozen();
this.name = name;
}
/// <summary>
/// Gets the logical name for this member in the schema (this is not critical for binary serialization, but may be used
/// when inferring a schema).
/// </summary>
public string Name
{
get { return Helpers.IsNullOrEmpty(name) ? member.Name : name; }
}
private const byte
OPTIONS_IsStrict = 1,
OPTIONS_IsPacked = 2,
OPTIONS_IsRequired = 4,
OPTIONS_OverwriteList = 8,
OPTIONS_SupportNull = 16;
private byte flags;
private bool HasFlag(byte flag)
{
return (flags & flag) == flag;
}
private void SetFlag(byte flag, bool value, bool throwIfFrozen)
{
if (throwIfFrozen && HasFlag(flag) != value)
{
ThrowIfFrozen();
}
if (value)
flags |= flag;
else
flags = (byte) (flags & ~flag);
}
/// <summary>
/// Should lists have extended support for null values? Note this makes the serialization less efficient.
/// </summary>
public bool SupportNull
{
get { return HasFlag(OPTIONS_SupportNull); }
set { SetFlag(OPTIONS_SupportNull, value, true); }
}
internal string GetSchemaTypeName(bool applyNetObjectProxy, ref bool requiresBclImport)
{
Type effectiveType = ItemType;
if (effectiveType == null) effectiveType = MemberType;
return model.GetSchemaTypeName(effectiveType, DataFormat, applyNetObjectProxy && asReference,
applyNetObjectProxy && dynamicType, ref requiresBclImport);
}
internal sealed class Comparer : System.Collections.IComparer
#if !NO_GENERICS
, System.Collections.Generic.IComparer<ValueMember>
#endif
{
public static readonly Comparer Default = new Comparer();
public int Compare(object x, object y)
{
return Compare(x as ValueMember, y as ValueMember);
}
public int Compare(ValueMember x, ValueMember y)
{
if (ReferenceEquals(x, y)) return 0;
if (x == null) return -1;
if (y == null) return 1;
return x.FieldNumber.CompareTo(y.FieldNumber);
}
}
}
}
#endif

View File

@ -1,255 +0,0 @@
using System;
using System.Collections;
using ProtoBuf.Meta;
namespace ProtoBuf
{
internal sealed class NetObjectCache
{
internal const int Root = 0;
private MutableList underlyingList;
private MutableList List
{
get
{
if (underlyingList == null) underlyingList = new MutableList();
return underlyingList;
}
}
internal object GetKeyedObject(int key)
{
if (key-- == Root)
{
if (rootObject == null) throw new ProtoException("No root object assigned");
return rootObject;
}
BasicList list = List;
if (key < 0 || key >= list.Count)
{
Helpers.DebugWriteLine("Missing key: " + key);
throw new ProtoException("Internal error; a missing key occurred");
}
object tmp = list[key];
if (tmp == null)
{
throw new ProtoException("A deferred key does not have a value yet");
}
return tmp;
}
internal void SetKeyedObject(int key, object value)
{
if (key-- == Root)
{
if (value == null) throw new ArgumentNullException("value");
if (rootObject != null && ((object) rootObject != (object) value))
throw new ProtoException("The root object cannot be reassigned");
rootObject = value;
}
else
{
MutableList list = List;
if (key < list.Count)
{
object oldVal = list[key];
if (oldVal == null)
{
list[key] = value;
}
else if (!ReferenceEquals(oldVal, value))
{
throw new ProtoException("Reference-tracked objects cannot change reference");
} // otherwise was the same; nothing to do
}
else if (key != list.Add(value))
{
throw new ProtoException("Internal error; a key mismatch occurred");
}
}
}
private object rootObject;
internal int AddObjectKey(object value, out bool existing)
{
if (value == null) throw new ArgumentNullException("value");
if ((object) value == (object) rootObject) // (object) here is no-op, but should be
{
// preserved even if this was typed - needs ref-check
existing = true;
return Root;
}
string s = value as string;
BasicList list = List;
int index;
#if NO_GENERICS
if(s == null)
{
if (objectKeys == null)
{
objectKeys = new ReferenceHashtable();
index = -1;
}
else
{
object tmp = objectKeys[value];
index = tmp == null ? -1 : (int) tmp;
}
}
else
{
if (stringKeys == null)
{
stringKeys = new Hashtable();
index = -1;
}
else
{
object tmp = stringKeys[s];
index = tmp == null ? -1 : (int) tmp;
}
}
#else
if (s == null)
{
#if CF || PORTABLE // CF has very limited proper object ref-tracking; so instead, we'll search it the hard way
index = list.IndexOfReference(value);
#else
if (objectKeys == null)
{
objectKeys = new System.Collections.Generic.Dictionary<object, int>(ReferenceComparer.Default);
index = -1;
}
else
{
if (!objectKeys.TryGetValue(value, out index)) index = -1;
}
#endif
}
else
{
if (stringKeys == null)
{
stringKeys = new System.Collections.Generic.Dictionary<string, int>();
index = -1;
}
else
{
if (!stringKeys.TryGetValue(s, out index)) index = -1;
}
}
#endif
if (!(existing = index >= 0))
{
index = list.Add(value);
if (s == null)
{
#if !CF && !PORTABLE // CF can't handle the object keys very well
objectKeys.Add(value, index);
#endif
}
else
{
stringKeys.Add(s, index);
}
}
return index + 1;
}
private int trapStartIndex; // defaults to 0 - optimization for RegisterTrappedObject
// to make it faster at seeking to find deferred-objects
internal void RegisterTrappedObject(object value)
{
if (rootObject == null)
{
rootObject = value;
}
else
{
if (underlyingList != null)
{
for (int i = trapStartIndex; i < underlyingList.Count; i++)
{
trapStartIndex = i + 1; // things never *become* null; whether or
// not the next item is null, it will never
// need to be checked again
if (underlyingList[i] == null)
{
underlyingList[i] = value;
break;
}
}
}
}
}
#if NO_GENERICS
private ReferenceHashtable objectKeys;
private System.Collections.Hashtable stringKeys;
private class ReferenceHashtable : System.Collections.Hashtable
{
protected override int GetHash(object key)
{
return System.Runtime.CompilerServices.RuntimeHelpers.GetHashCode(key);
}
protected override bool KeyEquals(object item, object key)
{
return item == key;
}
}
#else
private System.Collections.Generic.Dictionary<string, int> stringKeys;
#if !CF && !PORTABLE
// CF lacks the ability to get a robust reference-based hash-code, so we'll do it the harder way instead
private System.Collections.Generic.Dictionary<object, int> objectKeys;
private sealed class ReferenceComparer : System.Collections.Generic.IEqualityComparer<object>
{
public static readonly ReferenceComparer Default = new ReferenceComparer();
private ReferenceComparer()
{
}
bool System.Collections.Generic.IEqualityComparer<object>.Equals(object x, object y)
{
return x == y; // ref equality
}
int System.Collections.Generic.IEqualityComparer<object>.GetHashCode(object obj)
{
return System.Runtime.CompilerServices.RuntimeHelpers.GetHashCode(obj);
}
}
#endif
#endif
internal void Clear()
{
trapStartIndex = 0;
rootObject = null;
if (underlyingList != null) underlyingList.Clear();
if (stringKeys != null) stringKeys.Clear();
#if !CF && !PORTABLE
if (objectKeys != null) objectKeys.Clear();
#endif
}
}
}

View File

@ -1,28 +0,0 @@
namespace ProtoBuf
{
/// <summary>
/// Specifies the type of prefix that should be applied to messages.
/// </summary>
public enum PrefixStyle
{
/// <summary>
/// No length prefix is applied to the data; the data is terminated only be the end of the stream.
/// </summary>
None,
/// <summary>
/// A base-128 length prefix is applied to the data (efficient for short messages).
/// </summary>
Base128,
/// <summary>
/// A fixed-length (little-endian) length prefix is applied to the data (useful for compatibility).
/// </summary>
Fixed32,
/// <summary>
/// A fixed-length (big-endian) length prefix is applied to the data (useful for compatibility).
/// </summary>
Fixed32BigEndian
}
}

View File

@ -1,183 +0,0 @@
using System;
namespace ProtoBuf
{
/// <summary>
/// Indicates that a type is defined for protocol-buffer serialization.
/// </summary>
[AttributeUsage(
AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Interface,
AllowMultiple = false, Inherited = false)]
public sealed class ProtoContractAttribute : Attribute
{
/// <summary>
/// Gets or sets the defined name of the type.
/// </summary>
public string Name
{
get { return name; }
set { name = value; }
}
private string name;
/// <summary>
/// Gets or sets the fist offset to use with implicit field tags;
/// only uesd if ImplicitFields is set.
/// </summary>
public int ImplicitFirstTag
{
get { return implicitFirstTag; }
set
{
if (value < 1) throw new ArgumentOutOfRangeException("ImplicitFirstTag");
implicitFirstTag = value;
}
}
private int implicitFirstTag;
/// <summary>
/// If specified, alternative contract markers (such as markers for XmlSerailizer or DataContractSerializer) are ignored.
/// </summary>
public bool UseProtoMembersOnly
{
get { return HasFlag(OPTIONS_UseProtoMembersOnly); }
set { SetFlag(OPTIONS_UseProtoMembersOnly, value); }
}
/// <summary>
/// If specified, do NOT treat this type as a list, even if it looks like one.
/// </summary>
public bool IgnoreListHandling
{
get { return HasFlag(OPTIONS_IgnoreListHandling); }
set { SetFlag(OPTIONS_IgnoreListHandling, value); }
}
/// <summary>
/// Gets or sets the mechanism used to automatically infer field tags
/// for members. This option should be used in advanced scenarios only.
/// Please review the important notes against the ImplicitFields enumeration.
/// </summary>
public ImplicitFields ImplicitFields
{
get { return implicitFields; }
set { implicitFields = value; }
}
private ImplicitFields implicitFields;
/// <summary>
/// Enables/disables automatic tag generation based on the existing name / order
/// of the defined members. This option is not used for members marked
/// with ProtoMemberAttribute, as intended to provide compatibility with
/// WCF serialization. WARNING: when adding new fields you must take
/// care to increase the Order for new elements, otherwise data corruption
/// may occur.
/// </summary>
/// <remarks>If not explicitly specified, the default is assumed from Serializer.GlobalOptions.InferTagFromName.</remarks>
public bool InferTagFromName
{
get { return HasFlag(OPTIONS_InferTagFromName); }
set
{
SetFlag(OPTIONS_InferTagFromName, value);
SetFlag(OPTIONS_InferTagFromNameHasValue, true);
}
}
/// <summary>
/// Has a InferTagFromName value been explicitly set? if not, the default from the type-model is assumed.
/// </summary>
internal bool InferTagFromNameHasValue
{
// note that this property is accessed via reflection and should not be removed
get { return HasFlag(OPTIONS_InferTagFromNameHasValue); }
}
private int dataMemberOffset;
/// <summary>
/// Specifies an offset to apply to [DataMember(Order=...)] markers;
/// this is useful when working with mex-generated classes that have
/// a different origin (usually 1 vs 0) than the original data-contract.
///
/// This value is added to the Order of each member.
/// </summary>
public int DataMemberOffset
{
get { return dataMemberOffset; }
set { dataMemberOffset = value; }
}
/// <summary>
/// If true, the constructor for the type is bypassed during deserialization, meaning any field initializers
/// or other initialization code is skipped.
/// </summary>
public bool SkipConstructor
{
get { return HasFlag(OPTIONS_SkipConstructor); }
set { SetFlag(OPTIONS_SkipConstructor, value); }
}
/// <summary>
/// Should this type be treated as a reference by default? Please also see the implications of this,
/// as recorded on ProtoMemberAttribute.AsReference
/// </summary>
public bool AsReferenceDefault
{
get { return HasFlag(OPTIONS_AsReferenceDefault); }
set { SetFlag(OPTIONS_AsReferenceDefault, value); }
}
private bool HasFlag(byte flag)
{
return (flags & flag) == flag;
}
private void SetFlag(byte flag, bool value)
{
if (value) flags |= flag;
else flags = (byte) (flags & ~flag);
}
private byte flags;
private const byte
OPTIONS_InferTagFromName = 1,
OPTIONS_InferTagFromNameHasValue = 2,
OPTIONS_UseProtoMembersOnly = 4,
OPTIONS_SkipConstructor = 8,
OPTIONS_IgnoreListHandling = 16,
OPTIONS_AsReferenceDefault = 32,
OPTIONS_EnumPassthru = 64,
OPTIONS_EnumPassthruHasValue = 128;
/// <summary>
/// Applies only to enums (not to DTO classes themselves); gets or sets a value indicating that an enum should be treated directly as an int/short/etc, rather
/// than enforcing .proto enum rules. This is useful *in particul* for [Flags] enums.
/// </summary>
public bool EnumPassthru
{
get { return HasFlag(OPTIONS_EnumPassthru); }
set
{
SetFlag(OPTIONS_EnumPassthru, value);
SetFlag(OPTIONS_EnumPassthruHasValue, true);
}
}
/// <summary>
/// Has a EnumPassthru value been explicitly set?
/// </summary>
internal bool EnumPassthruHasValue
{
// note that this property is accessed via reflection and should not be removed
get { return HasFlag(OPTIONS_EnumPassthruHasValue); }
}
}
}

View File

@ -1,15 +0,0 @@
using System;
namespace ProtoBuf
{
/// <summary>
/// Indicates that a static member should be considered the same as though
/// were an implicit / explicit conversion operator; in particular, this
/// is useful for conversions that operator syntax does not allow, such as
/// to/from interface types.
/// </summary>
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
public class ProtoConverterAttribute : Attribute
{
}
}

View File

@ -1,49 +0,0 @@
using System;
namespace ProtoBuf
{
/// <summary>
/// Used to define protocol-buffer specific behavior for
/// enumerated values.
/// </summary>
[AttributeUsage(AttributeTargets.Field, AllowMultiple = false)]
public sealed class ProtoEnumAttribute : Attribute
{
/// <summary>
/// Gets or sets the specific value to use for this enum during serialization.
/// </summary>
public int Value
{
get { return enumValue; }
set
{
this.enumValue = value;
hasValue = true;
}
}
/// <summary>
/// Indicates whether this instance has a customised value mapping
/// </summary>
/// <returns>true if a specific value is set</returns>
public bool HasValue()
{
return hasValue;
}
private bool hasValue;
private int enumValue;
/// <summary>
/// Gets or sets the defined name of the enum, as used in .proto
/// (this name is not used during serialization).
/// </summary>
public string Name
{
get { return name; }
set { name = value; }
}
private string name;
}
}

View File

@ -1,37 +0,0 @@
using System;
#if PLAT_BINARYFORMATTER && !(WINRT || PHONE8)
using System.Runtime.Serialization;
#endif
namespace ProtoBuf
{
/// <summary>
/// Indicates an error during serialization/deserialization of a proto stream.
/// </summary>
#if PLAT_BINARYFORMATTER && !(WINRT || PHONE8)
[Serializable]
#endif
public class ProtoException : Exception
{
/// <summary>Creates a new ProtoException instance.</summary>
public ProtoException()
{
}
/// <summary>Creates a new ProtoException instance.</summary>
public ProtoException(string message) : base(message)
{
}
/// <summary>Creates a new ProtoException instance.</summary>
public ProtoException(string message, Exception innerException) : base(message, innerException)
{
}
#if PLAT_BINARYFORMATTER && !(WINRT || PHONE8)
/// <summary>Creates a new ProtoException instance.</summary>
protected ProtoException(SerializationInfo info, StreamingContext context) : base(info, context) { }
#endif
}
}

View File

@ -1,47 +0,0 @@
using System;
namespace ProtoBuf
{
/// <summary>
/// Indicates that a member should be excluded from serialization; this
/// is only normally used when using implict fields.
/// </summary>
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field,
AllowMultiple = false, Inherited = true)]
public class ProtoIgnoreAttribute : Attribute
{
}
/// <summary>
/// Indicates that a member should be excluded from serialization; this
/// is only normally used when using implict fields. This allows
/// ProtoIgnoreAttribute usage
/// even for partial classes where the individual members are not
/// under direct control.
/// </summary>
[AttributeUsage(AttributeTargets.Class,
AllowMultiple = true, Inherited = false)]
public sealed class ProtoPartialIgnoreAttribute : ProtoIgnoreAttribute
{
/// <summary>
/// Creates a new ProtoPartialIgnoreAttribute instance.
/// </summary>
/// <param name="memberName">Specifies the member to be ignored.</param>
public ProtoPartialIgnoreAttribute(string memberName)
: base()
{
if (Helpers.IsNullOrEmpty(memberName)) throw new ArgumentNullException("memberName");
this.memberName = memberName;
}
/// <summary>
/// The name of the member to be ignored.
/// </summary>
public string MemberName
{
get { return memberName; }
}
private readonly string memberName;
}
}

View File

@ -1,88 +0,0 @@
using System;
using System.ComponentModel;
using ProtoBuf.Meta;
#if FEAT_IKVM
using Type = IKVM.Reflection.Type;
using IKVM.Reflection;
#else
using System.Reflection;
#endif
namespace ProtoBuf
{
/// <summary>
/// Indicates the known-types to support for an individual
/// message. This serializes each level in the hierarchy as
/// a nested message to retain wire-compatibility with
/// other protocol-buffer implementations.
/// </summary>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface, AllowMultiple = true, Inherited = false)]
public sealed class ProtoIncludeAttribute : Attribute
{
///<summary>
/// Creates a new instance of the ProtoIncludeAttribute.
/// </summary>
/// <param name="tag">The unique index (within the type) that will identify this data.</param>
/// <param name="knownType">The additional type to serialize/deserialize.</param>
public ProtoIncludeAttribute(int tag, System.Type knownType)
: this(tag, knownType == null ? "" : knownType.AssemblyQualifiedName)
{
}
/// <summary>
/// Creates a new instance of the ProtoIncludeAttribute.
/// </summary>
/// <param name="tag">The unique index (within the type) that will identify this data.</param>
/// <param name="knownTypeName">The additional type to serialize/deserialize.</param>
public ProtoIncludeAttribute(int tag, string knownTypeName)
{
if (tag <= 0) throw new ArgumentOutOfRangeException("tag", "Tags must be positive integers");
if (Helpers.IsNullOrEmpty(knownTypeName))
throw new ArgumentNullException("knownTypeName", "Known type cannot be blank");
this.tag = tag;
this.knownTypeName = knownTypeName;
}
/// <summary>
/// Gets the unique index (within the type) that will identify this data.
/// </summary>
public int Tag
{
get { return tag; }
}
private readonly int tag;
/// <summary>
/// Gets the additional type to serialize/deserialize.
/// </summary>
public string KnownTypeName
{
get { return knownTypeName; }
}
private readonly string knownTypeName;
/// <summary>
/// Gets the additional type to serialize/deserialize.
/// </summary>
public Type KnownType
{
get { return TypeModel.ResolveKnownType(KnownTypeName, null, null); }
}
/// <summary>
/// Specifies whether the inherited sype's sub-message should be
/// written with a length-prefix (default), or with group markers.
/// </summary>
[DefaultValue(DataFormat.Default)]
public DataFormat DataFormat
{
get { return dataFormat; }
set { dataFormat = value; }
}
private DataFormat dataFormat = DataFormat.Default;
}
}

View File

@ -1,280 +0,0 @@
using System;
#if FEAT_IKVM
using Type = IKVM.Reflection.Type;
using IKVM.Reflection;
#else
using System.Reflection;
#endif
namespace ProtoBuf
{
/// <summary>
/// Declares a member to be used in protocol-buffer serialization, using
/// the given Tag. A DataFormat may be used to optimise the serialization
/// format (for instance, using zigzag encoding for negative numbers, or
/// fixed-length encoding for large values.
/// </summary>
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field,
AllowMultiple = false, Inherited = true)]
public class ProtoMemberAttribute : Attribute
, IComparable
#if !NO_GENERICS
, IComparable<ProtoMemberAttribute>
#endif
{
/// <summary>
/// Compare with another ProtoMemberAttribute for sorting purposes
/// </summary>
public int CompareTo(object other)
{
return CompareTo(other as ProtoMemberAttribute);
}
/// <summary>
/// Compare with another ProtoMemberAttribute for sorting purposes
/// </summary>
public int CompareTo(ProtoMemberAttribute other)
{
if (other == null) return -1;
if ((object) this == (object) other) return 0;
int result = this.tag.CompareTo(other.tag);
if (result == 0) result = string.CompareOrdinal(this.name, other.name);
return result;
}
/// <summary>
/// Creates a new ProtoMemberAttribute instance.
/// </summary>
/// <param name="tag">Specifies the unique tag used to identify this member within the type.</param>
public ProtoMemberAttribute(int tag) : this(tag, false)
{
}
internal ProtoMemberAttribute(int tag, bool forced)
{
if (tag <= 0 && !forced) throw new ArgumentOutOfRangeException("tag");
this.tag = tag;
}
#if !NO_RUNTIME
internal MemberInfo Member;
internal bool TagIsPinned;
#endif
/// <summary>
/// Gets or sets the original name defined in the .proto; not used
/// during serialization.
/// </summary>
public string Name
{
get { return name; }
set { name = value; }
}
private string name;
/// <summary>
/// Gets or sets the data-format to be used when encoding this value.
/// </summary>
public DataFormat DataFormat
{
get { return dataFormat; }
set { dataFormat = value; }
}
private DataFormat dataFormat;
/// <summary>
/// Gets the unique tag used to identify this member within the type.
/// </summary>
public int Tag
{
get { return tag; }
}
private int tag;
internal void Rebase(int tag)
{
this.tag = tag;
}
/// <summary>
/// Gets or sets a value indicating whether this member is mandatory.
/// </summary>
public bool IsRequired
{
get { return (options & MemberSerializationOptions.Required) == MemberSerializationOptions.Required; }
set
{
if (value) options |= MemberSerializationOptions.Required;
else options &= ~MemberSerializationOptions.Required;
}
}
/// <summary>
/// Gets a value indicating whether this member is packed.
/// This option only applies to list/array data of primitive types (int, double, etc).
/// </summary>
public bool IsPacked
{
get { return (options & MemberSerializationOptions.Packed) == MemberSerializationOptions.Packed; }
set
{
if (value) options |= MemberSerializationOptions.Packed;
else options &= ~MemberSerializationOptions.Packed;
}
}
/// <summary>
/// Indicates whether this field should *repace* existing values (the default is false, meaning *append*).
/// This option only applies to list/array data.
/// </summary>
public bool OverwriteList
{
get
{
return (options & MemberSerializationOptions.OverwriteList) == MemberSerializationOptions.OverwriteList;
}
set
{
if (value) options |= MemberSerializationOptions.OverwriteList;
else options &= ~MemberSerializationOptions.OverwriteList;
}
}
/// <summary>
/// Enables full object-tracking/full-graph support.
/// </summary>
public bool AsReference
{
get { return (options & MemberSerializationOptions.AsReference) == MemberSerializationOptions.AsReference; }
set
{
if (value) options |= MemberSerializationOptions.AsReference;
else options &= ~MemberSerializationOptions.AsReference;
options |= MemberSerializationOptions.AsReferenceHasValue;
}
}
internal bool AsReferenceHasValue
{
get
{
return (options & MemberSerializationOptions.AsReferenceHasValue) ==
MemberSerializationOptions.AsReferenceHasValue;
}
set
{
if (value) options |= MemberSerializationOptions.AsReferenceHasValue;
else options &= ~MemberSerializationOptions.AsReferenceHasValue;
}
}
/// <summary>
/// Embeds the type information into the stream, allowing usage with types not known in advance.
/// </summary>
public bool DynamicType
{
get { return (options & MemberSerializationOptions.DynamicType) == MemberSerializationOptions.DynamicType; }
set
{
if (value) options |= MemberSerializationOptions.DynamicType;
else options &= ~MemberSerializationOptions.DynamicType;
}
}
/// <summary>
/// Gets or sets a value indicating whether this member is packed (lists/arrays).
/// </summary>
public MemberSerializationOptions Options
{
get { return options; }
set { options = value; }
}
private MemberSerializationOptions options;
}
/// <summary>
/// Additional (optional) settings that control serialization of members
/// </summary>
[Flags]
public enum MemberSerializationOptions
{
/// <summary>
/// Default; no additional options
/// </summary>
None = 0,
/// <summary>
/// Indicates that repeated elements should use packed (length-prefixed) encoding
/// </summary>
Packed = 1,
/// <summary>
/// Indicates that the given item is required
/// </summary>
Required = 2,
/// <summary>
/// Enables full object-tracking/full-graph support
/// </summary>
AsReference = 4,
/// <summary>
/// Embeds the type information into the stream, allowing usage with types not known in advance
/// </summary>
DynamicType = 8,
/// <summary>
/// Indicates whether this field should *repace* existing values (the default is false, meaning *append*).
/// This option only applies to list/array data.
/// </summary>
OverwriteList = 16,
/// <summary>
/// Determines whether the types AsReferenceDefault value is used, or whether this member's AsReference should be used
/// </summary>
AsReferenceHasValue = 32
}
/// <summary>
/// Declares a member to be used in protocol-buffer serialization, using
/// the given Tag and MemberName. This allows ProtoMemberAttribute usage
/// even for partial classes where the individual members are not
/// under direct control.
/// A DataFormat may be used to optimise the serialization
/// format (for instance, using zigzag encoding for negative numbers, or
/// fixed-length encoding for large values.
/// </summary>
[AttributeUsage(AttributeTargets.Class,
AllowMultiple = true, Inherited = false)]
public sealed class ProtoPartialMemberAttribute : ProtoMemberAttribute
{
/// <summary>
/// Creates a new ProtoMemberAttribute instance.
/// </summary>
/// <param name="tag">Specifies the unique tag used to identify this member within the type.</param>
/// <param name="memberName">Specifies the member to be serialized.</param>
public ProtoPartialMemberAttribute(int tag, string memberName)
: base(tag)
{
if (Helpers.IsNullOrEmpty(memberName)) throw new ArgumentNullException("memberName");
this.memberName = memberName;
}
/// <summary>
/// The name of the member to be serialized.
/// </summary>
public string MemberName
{
get { return memberName; }
}
private readonly string memberName;
}
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -1,96 +0,0 @@
using System;
namespace ProtoBuf
{
/// <summary>
/// Additional information about a serialization operation
/// </summary>
public sealed class SerializationContext
{
private bool frozen;
internal void Freeze()
{
frozen = true;
}
private void ThrowIfFrozen()
{
if (frozen)
throw new InvalidOperationException("The serialization-context cannot be changed once it is in use");
}
private object context;
/// <summary>
/// Gets or sets a user-defined object containing additional information about this serialization/deserialization operation.
/// </summary>
public object Context
{
get { return context; }
set
{
if (context != value)
{
ThrowIfFrozen();
context = value;
}
}
}
private static readonly SerializationContext @default;
static SerializationContext()
{
@default = new SerializationContext();
@default.Freeze();
}
/// <summary>
/// A default SerializationContext, with minimal information.
/// </summary>
internal static SerializationContext Default
{
get { return @default; }
}
#if PLAT_BINARYFORMATTER || (SILVERLIGHT && NET_4_0)
#if !(WINRT || PHONE7 || PHONE8)
private System.Runtime.Serialization.StreamingContextStates state = System.Runtime.Serialization.StreamingContextStates.Persistence;
/// <summary>
/// Gets or sets the source or destination of the transmitted data.
/// </summary>
public System.Runtime.Serialization.StreamingContextStates State
{
get { return state; }
set { if (state != value) { ThrowIfFrozen(); state = value; } }
}
#endif
/// <summary>
/// Convert a SerializationContext to a StreamingContext
/// </summary>
public static implicit operator System.Runtime.Serialization.StreamingContext(SerializationContext ctx)
{
#if WINRT || PHONE7 || PHONE8
return new System.Runtime.Serialization.StreamingContext();
#else
if (ctx == null) return new System.Runtime.Serialization.StreamingContext(System.Runtime.Serialization.StreamingContextStates.Persistence);
return new System.Runtime.Serialization.StreamingContext(ctx.state, ctx.context);
#endif
}
/// <summary>
/// Convert a StreamingContext to a SerializationContext
/// </summary>
public static implicit operator SerializationContext (System.Runtime.Serialization.StreamingContext ctx)
{
SerializationContext result = new SerializationContext();
#if !(WINRT || PHONE7 || PHONE8)
result.Context = ctx.Context;
result.State = ctx.State;
#endif
return result;
}
#endif
}
}

View File

@ -1,547 +0,0 @@
using ProtoBuf.Meta;
using System;
using System.IO;
#if !NO_GENERICS
using System.Collections.Generic;
#endif
#if FEAT_IKVM
using Type = IKVM.Reflection.Type;
using IKVM.Reflection;
#else
using System.Reflection;
#endif
namespace ProtoBuf
{
/// <summary>
/// Provides protocol-buffer serialization capability for concrete, attributed types. This
/// is a *default* model, but custom serializer models are also supported.
/// </summary>
/// <remarks>
/// Protocol-buffer serialization is a compact binary format, designed to take
/// advantage of sparse data and knowledge of specific data types; it is also
/// extensible, allowing a type to be deserialized / merged even if some data is
/// not recognised.
/// </remarks>
public
#if FX11
sealed
#else
static
#endif
class Serializer
{
#if FX11
private Serializer() { } // not a static class for C# 1.2 reasons
#endif
#if !NO_RUNTIME && !NO_GENERICS
/// <summary>
/// Suggest a .proto definition for the given type
/// </summary>
/// <typeparam name="T">The type to generate a .proto definition for</typeparam>
/// <returns>The .proto definition as a string</returns>
public static string GetProto<T>()
{
return RuntimeTypeModel.Default.GetSchema(RuntimeTypeModel.Default.MapType(typeof (T)));
}
/// <summary>
/// Create a deep clone of the supplied instance; any sub-items are also cloned.
/// </summary>
public static T DeepClone<T>(T instance)
{
return instance == null ? instance : (T) RuntimeTypeModel.Default.DeepClone(instance);
}
/// <summary>
/// Applies a protocol-buffer stream to an existing instance.
/// </summary>
/// <typeparam name="T">The type being merged.</typeparam>
/// <param name="instance">The existing instance to be modified (can be null).</param>
/// <param name="source">The binary stream to apply to the instance (cannot be null).</param>
/// <returns>The updated instance; this may be different to the instance argument if
/// either the original instance was null, or the stream defines a known sub-type of the
/// original instance.</returns>
public static T Merge<T>(Stream source, T instance)
{
return (T) RuntimeTypeModel.Default.Deserialize(source, instance, typeof (T));
}
/// <summary>
/// Creates a new instance from a protocol-buffer stream
/// </summary>
/// <typeparam name="T">The type to be created.</typeparam>
/// <param name="source">The binary stream to apply to the new instance (cannot be null).</param>
/// <returns>A new, initialized instance.</returns>
public static T Deserialize<T>(Stream source)
{
return (T) RuntimeTypeModel.Default.Deserialize(source, null, typeof (T));
}
/// <summary>
/// Writes a protocol-buffer representation of the given instance to the supplied stream.
/// </summary>
/// <param name="instance">The existing instance to be serialized (cannot be null).</param>
/// <param name="destination">The destination stream to write to.</param>
public static void Serialize<T>(Stream destination, T instance)
{
if (instance != null)
{
RuntimeTypeModel.Default.Serialize(destination, instance);
}
}
/// <summary>
/// Serializes a given instance and deserializes it as a different type;
/// this can be used to translate between wire-compatible objects (where
/// two .NET types represent the same data), or to promote/demote a type
/// through an inheritance hierarchy.
/// </summary>
/// <remarks>No assumption of compatibility is made between the types.</remarks>
/// <typeparam name="TFrom">The type of the object being copied.</typeparam>
/// <typeparam name="TTo">The type of the new object to be created.</typeparam>
/// <param name="instance">The existing instance to use as a template.</param>
/// <returns>A new instane of type TNewType, with the data from TOldType.</returns>
public static TTo ChangeType<TFrom, TTo>(TFrom instance)
{
using (MemoryStream ms = new MemoryStream())
{
Serialize<TFrom>(ms, instance);
ms.Position = 0;
return Deserialize<TTo>(ms);
}
}
#if PLAT_BINARYFORMATTER && !(WINRT || PHONE8)
/// <summary>
/// Writes a protocol-buffer representation of the given instance to the supplied SerializationInfo.
/// </summary>
/// <typeparam name="T">The type being serialized.</typeparam>
/// <param name="instance">The existing instance to be serialized (cannot be null).</param>
/// <param name="info">The destination SerializationInfo to write to.</param>
public static void Serialize<T>(System.Runtime.Serialization.SerializationInfo info, T instance) where T : class, System.Runtime.Serialization.ISerializable
{
Serialize<T>(info, new System.Runtime.Serialization.StreamingContext(System.Runtime.Serialization.StreamingContextStates.Persistence), instance);
}
/// <summary>
/// Writes a protocol-buffer representation of the given instance to the supplied SerializationInfo.
/// </summary>
/// <typeparam name="T">The type being serialized.</typeparam>
/// <param name="instance">The existing instance to be serialized (cannot be null).</param>
/// <param name="info">The destination SerializationInfo to write to.</param>
/// <param name="context">Additional information about this serialization operation.</param>
public static void Serialize<T>(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context, T instance) where T : class, System.Runtime.Serialization.ISerializable
{
// note: also tried byte[]... it doesn't perform hugely well with either (compared to regular serialization)
if (info == null) throw new ArgumentNullException("info");
if (instance == null) throw new ArgumentNullException("instance");
if (instance.GetType() != typeof(T)) throw new ArgumentException("Incorrect type", "instance");
using (MemoryStream ms = new MemoryStream())
{
RuntimeTypeModel.Default.Serialize(ms, instance, context);
info.AddValue(ProtoBinaryField, ms.ToArray());
}
}
#endif
#if PLAT_XMLSERIALIZER
/// <summary>
/// Writes a protocol-buffer representation of the given instance to the supplied XmlWriter.
/// </summary>
/// <typeparam name="T">The type being serialized.</typeparam>
/// <param name="instance">The existing instance to be serialized (cannot be null).</param>
/// <param name="writer">The destination XmlWriter to write to.</param>
public static void Serialize<T>(System.Xml.XmlWriter writer, T instance) where T : System.Xml.Serialization.IXmlSerializable
{
if (writer == null) throw new ArgumentNullException("writer");
if (instance == null) throw new ArgumentNullException("instance");
using (MemoryStream ms = new MemoryStream())
{
Serializer.Serialize(ms, instance);
writer.WriteBase64(ms.GetBuffer(), 0, (int)ms.Length);
}
}
/// <summary>
/// Applies a protocol-buffer from an XmlReader to an existing instance.
/// </summary>
/// <typeparam name="T">The type being merged.</typeparam>
/// <param name="instance">The existing instance to be modified (cannot be null).</param>
/// <param name="reader">The XmlReader containing the data to apply to the instance (cannot be null).</param>
public static void Merge<T>(System.Xml.XmlReader reader, T instance) where T : System.Xml.Serialization.IXmlSerializable
{
if (reader == null) throw new ArgumentNullException("reader");
if (instance == null) throw new ArgumentNullException("instance");
const int LEN = 4096;
byte[] buffer = new byte[LEN];
int read;
using (MemoryStream ms = new MemoryStream())
{
int depth = reader.Depth;
while(reader.Read() && reader.Depth > depth)
{
if (reader.NodeType == System.Xml.XmlNodeType.Text)
{
while ((read = reader.ReadContentAsBase64(buffer, 0, LEN)) > 0)
{
ms.Write(buffer, 0, read);
}
if (reader.Depth <= depth) break;
}
}
ms.Position = 0;
Serializer.Merge(ms, instance);
}
}
#endif
private const string ProtoBinaryField = "proto";
#if PLAT_BINARYFORMATTER && !NO_GENERICS && !(WINRT || PHONE8)
/// <summary>
/// Applies a protocol-buffer from a SerializationInfo to an existing instance.
/// </summary>
/// <typeparam name="T">The type being merged.</typeparam>
/// <param name="instance">The existing instance to be modified (cannot be null).</param>
/// <param name="info">The SerializationInfo containing the data to apply to the instance (cannot be null).</param>
public static void Merge<T>(System.Runtime.Serialization.SerializationInfo info, T instance) where T : class, System.Runtime.Serialization.ISerializable
{
Merge<T>(info, new System.Runtime.Serialization.StreamingContext(System.Runtime.Serialization.StreamingContextStates.Persistence), instance);
}
/// <summary>
/// Applies a protocol-buffer from a SerializationInfo to an existing instance.
/// </summary>
/// <typeparam name="T">The type being merged.</typeparam>
/// <param name="instance">The existing instance to be modified (cannot be null).</param>
/// <param name="info">The SerializationInfo containing the data to apply to the instance (cannot be null).</param>
/// <param name="context">Additional information about this serialization operation.</param>
public static void Merge<T>(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context, T instance) where T : class, System.Runtime.Serialization.ISerializable
{
// note: also tried byte[]... it doesn't perform hugely well with either (compared to regular serialization)
if (info == null) throw new ArgumentNullException("info");
if (instance == null) throw new ArgumentNullException("instance");
if (instance.GetType() != typeof(T)) throw new ArgumentException("Incorrect type", "instance");
byte[] buffer = (byte[])info.GetValue(ProtoBinaryField, typeof(byte[]));
using (MemoryStream ms = new MemoryStream(buffer))
{
T result = (T)RuntimeTypeModel.Default.Deserialize(ms, instance, typeof(T), context);
if (!ReferenceEquals(result, instance))
{
throw new ProtoException("Deserialization changed the instance; cannot succeed.");
}
}
}
#endif
#if !NO_GENERICS
/// <summary>
/// Precompiles the serializer for a given type.
/// </summary>
public static void PrepareSerializer<T>()
{
#if FEAT_COMPILER
RuntimeTypeModel model = RuntimeTypeModel.Default;
model[model.MapType(typeof(T))].CompileInPlace();
#endif
}
#if PLAT_BINARYFORMATTER && !(WINRT || PHONE8)
/// <summary>
/// Creates a new IFormatter that uses protocol-buffer [de]serialization.
/// </summary>
/// <typeparam name="T">The type of object to be [de]deserialized by the formatter.</typeparam>
/// <returns>A new IFormatter to be used during [de]serialization.</returns>
public static System.Runtime.Serialization.IFormatter CreateFormatter<T>()
{
#if FEAT_IKVM
throw new NotSupportedException();
#else
return RuntimeTypeModel.Default.CreateFormatter(typeof(T));
#endif
}
#endif
/// <summary>
/// Reads a sequence of consecutive length-prefixed items from a stream, using
/// either base-128 or fixed-length prefixes. Base-128 prefixes with a tag
/// are directly comparable to serializing multiple items in succession
/// (use the <see cref="ListItemTag"/> tag to emulate the implicit behavior
/// when serializing a list/array). When a tag is
/// specified, any records with different tags are silently omitted. The
/// tag is ignored. The tag is ignores for fixed-length prefixes.
/// </summary>
/// <typeparam name="T">The type of object to deserialize.</typeparam>
/// <param name="source">The binary stream containing the serialized records.</param>
/// <param name="style">The prefix style used in the data.</param>
/// <param name="fieldNumber">The tag of records to return (if non-positive, then no tag is
/// expected and all records are returned).</param>
/// <returns>The sequence of deserialized objects.</returns>
public static IEnumerable<T> DeserializeItems<T>(Stream source, PrefixStyle style, int fieldNumber)
{
return RuntimeTypeModel.Default.DeserializeItems<T>(source, style, fieldNumber);
}
/// <summary>
/// Creates a new instance from a protocol-buffer stream that has a length-prefix
/// on data (to assist with network IO).
/// </summary>
/// <typeparam name="T">The type to be created.</typeparam>
/// <param name="source">The binary stream to apply to the new instance (cannot be null).</param>
/// <param name="style">How to encode the length prefix.</param>
/// <returns>A new, initialized instance.</returns>
public static T DeserializeWithLengthPrefix<T>(Stream source, PrefixStyle style)
{
return DeserializeWithLengthPrefix<T>(source, style, 0);
}
/// <summary>
/// Creates a new instance from a protocol-buffer stream that has a length-prefix
/// on data (to assist with network IO).
/// </summary>
/// <typeparam name="T">The type to be created.</typeparam>
/// <param name="source">The binary stream to apply to the new instance (cannot be null).</param>
/// <param name="style">How to encode the length prefix.</param>
/// <param name="fieldNumber">The expected tag of the item (only used with base-128 prefix style).</param>
/// <returns>A new, initialized instance.</returns>
public static T DeserializeWithLengthPrefix<T>(Stream source, PrefixStyle style, int fieldNumber)
{
RuntimeTypeModel model = RuntimeTypeModel.Default;
return (T) model.DeserializeWithLengthPrefix(source, null, model.MapType(typeof (T)), style, fieldNumber);
}
/// <summary>
/// Applies a protocol-buffer stream to an existing instance, using length-prefixed
/// data - useful with network IO.
/// </summary>
/// <typeparam name="T">The type being merged.</typeparam>
/// <param name="instance">The existing instance to be modified (can be null).</param>
/// <param name="source">The binary stream to apply to the instance (cannot be null).</param>
/// <param name="style">How to encode the length prefix.</param>
/// <returns>The updated instance; this may be different to the instance argument if
/// either the original instance was null, or the stream defines a known sub-type of the
/// original instance.</returns>
public static T MergeWithLengthPrefix<T>(Stream source, T instance, PrefixStyle style)
{
RuntimeTypeModel model = RuntimeTypeModel.Default;
return (T) model.DeserializeWithLengthPrefix(source, instance, model.MapType(typeof (T)), style, 0);
}
/// <summary>
/// Writes a protocol-buffer representation of the given instance to the supplied stream,
/// with a length-prefix. This is useful for socket programming,
/// as DeserializeWithLengthPrefix/MergeWithLengthPrefix can be used to read the single object back
/// from an ongoing stream.
/// </summary>
/// <typeparam name="T">The type being serialized.</typeparam>
/// <param name="instance">The existing instance to be serialized (cannot be null).</param>
/// <param name="style">How to encode the length prefix.</param>
/// <param name="destination">The destination stream to write to.</param>
public static void SerializeWithLengthPrefix<T>(Stream destination, T instance, PrefixStyle style)
{
SerializeWithLengthPrefix<T>(destination, instance, style, 0);
}
/// <summary>
/// Writes a protocol-buffer representation of the given instance to the supplied stream,
/// with a length-prefix. This is useful for socket programming,
/// as DeserializeWithLengthPrefix/MergeWithLengthPrefix can be used to read the single object back
/// from an ongoing stream.
/// </summary>
/// <typeparam name="T">The type being serialized.</typeparam>
/// <param name="instance">The existing instance to be serialized (cannot be null).</param>
/// <param name="style">How to encode the length prefix.</param>
/// <param name="destination">The destination stream to write to.</param>
/// <param name="fieldNumber">The tag used as a prefix to each record (only used with base-128 style prefixes).</param>
public static void SerializeWithLengthPrefix<T>(Stream destination, T instance, PrefixStyle style,
int fieldNumber)
{
RuntimeTypeModel model = RuntimeTypeModel.Default;
model.SerializeWithLengthPrefix(destination, instance, model.MapType(typeof (T)), style, fieldNumber);
}
#endif
/// <summary>Indicates the number of bytes expected for the next message.</summary>
/// <param name="source">The stream containing the data to investigate for a length.</param>
/// <param name="style">The algorithm used to encode the length.</param>
/// <param name="length">The length of the message, if it could be identified.</param>
/// <returns>True if a length could be obtained, false otherwise.</returns>
public static bool TryReadLengthPrefix(Stream source, PrefixStyle style, out int length)
{
int fieldNumber, bytesRead;
length = ProtoReader.ReadLengthPrefix(source, false, style, out fieldNumber, out bytesRead);
return bytesRead > 0;
}
/// <summary>Indicates the number of bytes expected for the next message.</summary>
/// <param name="buffer">The buffer containing the data to investigate for a length.</param>
/// <param name="index">The offset of the first byte to read from the buffer.</param>
/// <param name="count">The number of bytes to read from the buffer.</param>
/// <param name="style">The algorithm used to encode the length.</param>
/// <param name="length">The length of the message, if it could be identified.</param>
/// <returns>True if a length could be obtained, false otherwise.</returns>
public static bool TryReadLengthPrefix(byte[] buffer, int index, int count, PrefixStyle style, out int length)
{
using (Stream source = new MemoryStream(buffer, index, count))
{
return TryReadLengthPrefix(source, style, out length);
}
}
#endif
/// <summary>
/// The field number that is used as a default when serializing/deserializing a list of objects.
/// The data is treated as repeated message with field number 1.
/// </summary>
public const int ListItemTag = 1;
#if !NO_RUNTIME
/// <summary>
/// Provides non-generic access to the default serializer.
/// </summary>
public
#if FX11
sealed
#else
static
#endif
class NonGeneric
{
#if FX11
private NonGeneric() { } // not a static class for C# 1.2 reasons
#endif
/// <summary>
/// Create a deep clone of the supplied instance; any sub-items are also cloned.
/// </summary>
public static object DeepClone(object instance)
{
return instance == null ? null : RuntimeTypeModel.Default.DeepClone(instance);
}
/// <summary>
/// Writes a protocol-buffer representation of the given instance to the supplied stream.
/// </summary>
/// <param name="instance">The existing instance to be serialized (cannot be null).</param>
/// <param name="dest">The destination stream to write to.</param>
public static void Serialize(Stream dest, object instance)
{
if (instance != null)
{
RuntimeTypeModel.Default.Serialize(dest, instance);
}
}
/// <summary>
/// Creates a new instance from a protocol-buffer stream
/// </summary>
/// <param name="type">The type to be created.</param>
/// <param name="source">The binary stream to apply to the new instance (cannot be null).</param>
/// <returns>A new, initialized instance.</returns>
public static object Deserialize(System.Type type, Stream source)
{
return RuntimeTypeModel.Default.Deserialize(source, null, type);
}
/// <summary>Applies a protocol-buffer stream to an existing instance.</summary>
/// <param name="instance">The existing instance to be modified (cannot be null).</param>
/// <param name="source">The binary stream to apply to the instance (cannot be null).</param>
/// <returns>The updated instance</returns>
public static object Merge(Stream source, object instance)
{
if (instance == null) throw new ArgumentNullException("instance");
return RuntimeTypeModel.Default.Deserialize(source, instance, instance.GetType(), null);
}
/// <summary>
/// Writes a protocol-buffer representation of the given instance to the supplied stream,
/// with a length-prefix. This is useful for socket programming,
/// as DeserializeWithLengthPrefix/MergeWithLengthPrefix can be used to read the single object back
/// from an ongoing stream.
/// </summary>
/// <param name="instance">The existing instance to be serialized (cannot be null).</param>
/// <param name="style">How to encode the length prefix.</param>
/// <param name="destination">The destination stream to write to.</param>
/// <param name="fieldNumber">The tag used as a prefix to each record (only used with base-128 style prefixes).</param>
public static void SerializeWithLengthPrefix(Stream destination, object instance, PrefixStyle style,
int fieldNumber)
{
if (instance == null) throw new ArgumentNullException("instance");
RuntimeTypeModel model = RuntimeTypeModel.Default;
model.SerializeWithLengthPrefix(destination, instance, model.MapType(instance.GetType()), style,
fieldNumber);
}
/// <summary>
/// Applies a protocol-buffer stream to an existing instance (or null), using length-prefixed
/// data - useful with network IO.
/// </summary>
/// <param name="value">The existing instance to be modified (can be null).</param>
/// <param name="source">The binary stream to apply to the instance (cannot be null).</param>
/// <param name="style">How to encode the length prefix.</param>
/// <param name="resolver">Used to resolve types on a per-field basis.</param>
/// <returns>The updated instance; this may be different to the instance argument if
/// either the original instance was null, or the stream defines a known sub-type of the
/// original instance.</returns>
public static bool TryDeserializeWithLengthPrefix(Stream source, PrefixStyle style, TypeResolver resolver,
out object value)
{
value = RuntimeTypeModel.Default.DeserializeWithLengthPrefix(source, null, null, style, 0, resolver);
return value != null;
}
/// <summary>
/// Indicates whether the supplied type is explicitly modelled by the model
/// </summary>
public static bool CanSerialize(Type type)
{
return RuntimeTypeModel.Default.IsDefined(type);
}
}
/// <summary>
/// Global switches that change the behavior of protobuf-net
/// </summary>
public
#if FX11
sealed
#else
static
#endif
class GlobalOptions
{
#if FX11
private GlobalOptions() { } // not a static class for C# 1.2 reasons
#endif
/// <summary>
/// <see cref="RuntimeTypeModel.InferTagFromNameDefault"/>
/// </summary>
[Obsolete("Please use RuntimeTypeModel.Default.InferTagFromNameDefault instead (or on a per-model basis)",
false)]
public static bool InferTagFromName
{
get { return RuntimeTypeModel.Default.InferTagFromNameDefault; }
set { RuntimeTypeModel.Default.InferTagFromNameDefault = value; }
}
}
#endif
/// <summary>
/// Maps a field-number to a type
/// </summary>
public delegate Type TypeResolver(int fieldNumber);
/// <summary>
/// Releases any internal buffers that have been reserved for efficiency; this does not affect any serialization
/// operations; simply: it can be used (optionally) to release the buffers for garbage collection (at the expense
/// of having to re-allocate a new buffer for the next operation, rather than re-use prior buffers).
/// </summary>
public static void FlushPool()
{
BufferPool.Flush();
}
}
}

View File

@ -1,300 +0,0 @@
#if !NO_RUNTIME
using System;
using System.Collections;
using ProtoBuf.Meta;
#if FEAT_IKVM
using Type = IKVM.Reflection.Type;
using IKVM.Reflection;
#else
using System.Reflection;
#endif
namespace ProtoBuf.Serializers
{
internal sealed class ArrayDecorator : ProtoDecoratorBase
{
private readonly int fieldNumber;
private const byte
OPTIONS_WritePacked = 1,
OPTIONS_OverwriteList = 2,
OPTIONS_SupportNull = 4;
private readonly byte options;
private readonly WireType packedWireType;
public ArrayDecorator(TypeModel model, IProtoSerializer tail, int fieldNumber, bool writePacked,
WireType packedWireType, Type arrayType, bool overwriteList, bool supportNull)
: base(tail)
{
Helpers.DebugAssert(arrayType != null, "arrayType should be non-null");
Helpers.DebugAssert(arrayType.IsArray && arrayType.GetArrayRank() == 1,
"should be single-dimension array; " + arrayType.FullName);
this.itemType = arrayType.GetElementType();
#if NO_GENERICS
Type underlyingItemType = itemType;
#else
Type underlyingItemType = supportNull ? itemType : (Helpers.GetUnderlyingType(itemType) ?? itemType);
#endif
Helpers.DebugAssert(underlyingItemType == Tail.ExpectedType, "invalid tail");
Helpers.DebugAssert(Tail.ExpectedType != model.MapType(typeof (byte)), "Should have used BlobSerializer");
if ((writePacked || packedWireType != WireType.None) && fieldNumber <= 0)
throw new ArgumentOutOfRangeException("fieldNumber");
if (!ListDecorator.CanPack(packedWireType))
{
if (writePacked) throw new InvalidOperationException("Only simple data-types can use packed encoding");
packedWireType = WireType.None;
}
this.fieldNumber = fieldNumber;
this.packedWireType = packedWireType;
if (writePacked) options |= OPTIONS_WritePacked;
if (overwriteList) options |= OPTIONS_OverwriteList;
if (supportNull) options |= OPTIONS_SupportNull;
this.arrayType = arrayType;
}
private readonly Type arrayType, itemType; // this is, for example, typeof(int[])
public override Type ExpectedType
{
get { return arrayType; }
}
public override bool RequiresOldValue
{
get { return AppendToCollection; }
}
public override bool ReturnsValue
{
get { return true; }
}
#if FEAT_COMPILER
protected override void EmitWrite(ProtoBuf.Compiler.CompilerContext ctx, ProtoBuf.Compiler.Local valueFrom)
{
// int i and T[] arr
using (Compiler.Local arr = ctx.GetLocalWithValue(arrayType, valueFrom))
using (Compiler.Local i = new ProtoBuf.Compiler.Local(ctx, ctx.MapType(typeof(int))))
{
bool writePacked = (options & OPTIONS_WritePacked) != 0;
using (Compiler.Local token = writePacked ? new Compiler.Local(ctx, ctx.MapType(typeof(SubItemToken))) : null)
{
Type mappedWriter = ctx.MapType(typeof (ProtoWriter));
if (writePacked)
{
ctx.LoadValue(fieldNumber);
ctx.LoadValue((int)WireType.String);
ctx.LoadReaderWriter();
ctx.EmitCall(mappedWriter.GetMethod("WriteFieldHeader"));
ctx.LoadValue(arr);
ctx.LoadReaderWriter();
ctx.EmitCall(mappedWriter.GetMethod("StartSubItem"));
ctx.StoreValue(token);
ctx.LoadValue(fieldNumber);
ctx.LoadReaderWriter();
ctx.EmitCall(mappedWriter.GetMethod("SetPackedField"));
}
EmitWriteArrayLoop(ctx, i, arr);
if (writePacked)
{
ctx.LoadValue(token);
ctx.LoadReaderWriter();
ctx.EmitCall(mappedWriter.GetMethod("EndSubItem"));
}
}
}
}
private void EmitWriteArrayLoop(Compiler.CompilerContext ctx, Compiler.Local i, Compiler.Local arr)
{
// i = 0
ctx.LoadValue(0);
ctx.StoreValue(i);
// range test is last (to minimise branches)
Compiler.CodeLabel loopTest = ctx.DefineLabel(), processItem = ctx.DefineLabel();
ctx.Branch(loopTest, false);
ctx.MarkLabel(processItem);
// {...}
ctx.LoadArrayValue(arr, i);
if (SupportNull)
{
Tail.EmitWrite(ctx, null);
}
else
{
ctx.WriteNullCheckedTail(itemType, Tail, null);
}
// i++
ctx.LoadValue(i);
ctx.LoadValue(1);
ctx.Add();
ctx.StoreValue(i);
// i < arr.Length
ctx.MarkLabel(loopTest);
ctx.LoadValue(i);
ctx.LoadLength(arr, false);
ctx.BranchIfLess(processItem, false);
}
#endif
private bool AppendToCollection
{
get { return (options & OPTIONS_OverwriteList) == 0; }
}
private bool SupportNull
{
get { return (options & OPTIONS_SupportNull) != 0; }
}
#if !FEAT_IKVM
public override void Write(object value, ProtoWriter dest)
{
IList arr = (IList) value;
int len = arr.Count;
SubItemToken token;
bool writePacked = (options & OPTIONS_WritePacked) != 0;
if (writePacked)
{
ProtoWriter.WriteFieldHeader(fieldNumber, WireType.String, dest);
token = ProtoWriter.StartSubItem(value, dest);
ProtoWriter.SetPackedField(fieldNumber, dest);
}
else
{
token = new SubItemToken(); // default
}
bool checkForNull = !SupportNull;
for (int i = 0; i < len; i++)
{
object obj = arr[i];
if (checkForNull && obj == null)
{
throw new NullReferenceException();
}
Tail.Write(obj, dest);
}
if (writePacked)
{
ProtoWriter.EndSubItem(token, dest);
}
}
public override object Read(object value, ProtoReader source)
{
int field = source.FieldNumber;
BasicList list = new BasicList();
if (packedWireType != WireType.None && source.WireType == WireType.String)
{
SubItemToken token = ProtoReader.StartSubItem(source);
while (ProtoReader.HasSubValue(packedWireType, source))
{
list.Add(Tail.Read(null, source));
}
ProtoReader.EndSubItem(token, source);
}
else
{
do
{
list.Add(Tail.Read(null, source));
} while (source.TryReadFieldHeader(field));
}
int oldLen = AppendToCollection ? ((value == null ? 0 : ((Array) value).Length)) : 0;
Array result = Array.CreateInstance(itemType, oldLen + list.Count);
if (oldLen != 0) ((Array) value).CopyTo(result, 0);
list.CopyTo(result, oldLen);
return result;
}
#endif
#if FEAT_COMPILER
protected override void EmitRead(ProtoBuf.Compiler.CompilerContext ctx, ProtoBuf.Compiler.Local valueFrom)
{
Type listType;
#if NO_GENERICS
listType = typeof(BasicList);
#else
listType = ctx.MapType(typeof(System.Collections.Generic.List<>)).MakeGenericType(itemType);
#endif
Type expected = ExpectedType;
using (Compiler.Local oldArr = AppendToCollection ? ctx.GetLocalWithValue(expected, valueFrom) : null)
using (Compiler.Local newArr = new Compiler.Local(ctx, expected))
using (Compiler.Local list = new Compiler.Local(ctx, listType))
{
ctx.EmitCtor(listType);
ctx.StoreValue(list);
ListDecorator.EmitReadList(ctx, list, Tail, listType.GetMethod("Add"), packedWireType, false);
// leave this "using" here, as it can share the "FieldNumber" local with EmitReadList
using(Compiler.Local oldLen = AppendToCollection ? new ProtoBuf.Compiler.Local(ctx, ctx.MapType(typeof(int))) : null) {
Type[] copyToArrayInt32Args = new Type[] { ctx.MapType(typeof(Array)), ctx.MapType(typeof(int)) };
if (AppendToCollection)
{
ctx.LoadLength(oldArr, true);
ctx.CopyValue();
ctx.StoreValue(oldLen);
ctx.LoadAddress(list, listType);
ctx.LoadValue(listType.GetProperty("Count"));
ctx.Add();
ctx.CreateArray(itemType, null); // length is on the stack
ctx.StoreValue(newArr);
ctx.LoadValue(oldLen);
Compiler.CodeLabel nothingToCopy = ctx.DefineLabel();
ctx.BranchIfFalse(nothingToCopy, true);
ctx.LoadValue(oldArr);
ctx.LoadValue(newArr);
ctx.LoadValue(0); // index in target
ctx.EmitCall(expected.GetMethod("CopyTo", copyToArrayInt32Args));
ctx.MarkLabel(nothingToCopy);
ctx.LoadValue(list);
ctx.LoadValue(newArr);
ctx.LoadValue(oldLen);
}
else
{
ctx.LoadAddress(list, listType);
ctx.LoadValue(listType.GetProperty("Count"));
ctx.CreateArray(itemType, null);
ctx.StoreValue(newArr);
ctx.LoadAddress(list, listType);
ctx.LoadValue(newArr);
ctx.LoadValue(0);
}
copyToArrayInt32Args[0] = expected; // // prefer: CopyTo(T[], int)
MethodInfo copyTo = listType.GetMethod("CopyTo", copyToArrayInt32Args);
if (copyTo == null)
{ // fallback: CopyTo(Array, int)
copyToArrayInt32Args[1] = ctx.MapType(typeof(Array));
copyTo = listType.GetMethod("CopyTo", copyToArrayInt32Args);
}
ctx.EmitCall(copyTo);
}
ctx.LoadValue(newArr);
}
}
#endif
}
}
#endif

View File

@ -1,80 +0,0 @@
#if !NO_RUNTIME
using System;
#if FEAT_COMPILER
using System.Reflection.Emit;
#endif
#if FEAT_IKVM
using Type = IKVM.Reflection.Type;
#endif
namespace ProtoBuf.Serializers
{
internal sealed class BlobSerializer : IProtoSerializer
{
public Type ExpectedType
{
get { return expectedType; }
}
#if FEAT_IKVM
readonly Type expectedType;
#else
private static readonly Type expectedType = typeof (byte[]);
#endif
public BlobSerializer(ProtoBuf.Meta.TypeModel model, bool overwriteList)
{
#if FEAT_IKVM
expectedType = model.MapType(typeof(byte[]));
#endif
this.overwriteList = overwriteList;
}
private readonly bool overwriteList;
#if !FEAT_IKVM
public object Read(object value, ProtoReader source)
{
return ProtoReader.AppendBytes(overwriteList ? null : (byte[]) value, source);
}
public void Write(object value, ProtoWriter dest)
{
ProtoWriter.WriteBytes((byte[]) value, dest);
}
#endif
bool IProtoSerializer.RequiresOldValue
{
get { return !overwriteList; }
}
bool IProtoSerializer.ReturnsValue
{
get { return true; }
}
#if FEAT_COMPILER
void IProtoSerializer.EmitWrite(Compiler.CompilerContext ctx, Compiler.Local valueFrom)
{
ctx.EmitBasicWrite("WriteBytes", valueFrom);
}
void IProtoSerializer.EmitRead(Compiler.CompilerContext ctx, Compiler.Local valueFrom)
{
if (overwriteList)
{
ctx.LoadNullRef();
}
else
{
ctx.LoadValue(valueFrom);
}
ctx.LoadReaderWriter();
ctx.EmitCall(ctx.MapType(typeof(ProtoReader)).GetMethod("AppendBytes"));
}
#endif
}
}
#endif

View File

@ -1,69 +0,0 @@
#if !NO_RUNTIME
using System;
#if FEAT_IKVM
using Type = IKVM.Reflection.Type;
using IKVM.Reflection;
#else
using System.Reflection;
#endif
namespace ProtoBuf.Serializers
{
internal sealed class BooleanSerializer : IProtoSerializer
{
#if FEAT_IKVM
readonly Type expectedType;
#else
private static readonly Type expectedType = typeof (bool);
#endif
public BooleanSerializer(ProtoBuf.Meta.TypeModel model)
{
#if FEAT_IKVM
expectedType = model.MapType(typeof(bool));
#endif
}
public Type ExpectedType
{
get { return expectedType; }
}
#if !FEAT_IKVM
public void Write(object value, ProtoWriter dest)
{
ProtoWriter.WriteBoolean((bool) value, dest);
}
public object Read(object value, ProtoReader source)
{
Helpers.DebugAssert(value == null); // since replaces
return source.ReadBoolean();
}
#endif
bool IProtoSerializer.RequiresOldValue
{
get { return false; }
}
bool IProtoSerializer.ReturnsValue
{
get { return true; }
}
#if FEAT_COMPILER
void IProtoSerializer.EmitWrite(Compiler.CompilerContext ctx, Compiler.Local valueFrom)
{
ctx.EmitBasicWrite("WriteBoolean", valueFrom);
}
void IProtoSerializer.EmitRead(Compiler.CompilerContext ctx, Compiler.Local valueFrom)
{
ctx.EmitBasicRead("ReadBoolean", ExpectedType);
}
#endif
}
}
#endif

View File

@ -1,66 +0,0 @@
#if !NO_RUNTIME
using System;
#if FEAT_IKVM
using Type = IKVM.Reflection.Type;
#endif
namespace ProtoBuf.Serializers
{
internal sealed class ByteSerializer : IProtoSerializer
{
public Type ExpectedType
{
get { return expectedType; }
}
#if FEAT_IKVM
readonly Type expectedType;
#else
private static readonly Type expectedType = typeof (byte);
#endif
public ByteSerializer(ProtoBuf.Meta.TypeModel model)
{
#if FEAT_IKVM
expectedType = model.MapType(typeof(byte));
#endif
}
bool IProtoSerializer.RequiresOldValue
{
get { return false; }
}
bool IProtoSerializer.ReturnsValue
{
get { return true; }
}
#if !FEAT_IKVM
public void Write(object value, ProtoWriter dest)
{
ProtoWriter.WriteByte((byte) value, dest);
}
public object Read(object value, ProtoReader source)
{
Helpers.DebugAssert(value == null); // since replaces
return source.ReadByte();
}
#endif
#if FEAT_COMPILER
void IProtoSerializer.EmitWrite(Compiler.CompilerContext ctx, Compiler.Local valueFrom)
{
ctx.EmitBasicWrite("WriteByte", valueFrom);
}
void IProtoSerializer.EmitRead(Compiler.CompilerContext ctx, Compiler.Local valueFrom)
{
ctx.EmitBasicRead("ReadByte", ExpectedType);
}
#endif
}
}
#endif

View File

@ -1,50 +0,0 @@
#if !NO_RUNTIME
using System;
#if FEAT_IKVM
using Type = IKVM.Reflection.Type;
using IKVM.Reflection;
#else
using System.Reflection;
#endif
namespace ProtoBuf.Serializers
{
internal sealed class CharSerializer : UInt16Serializer
{
#if FEAT_IKVM
readonly Type expectedType;
#else
private static readonly Type expectedType = typeof (char);
#endif
public CharSerializer(ProtoBuf.Meta.TypeModel model) : base(model)
{
#if FEAT_IKVM
expectedType = model.MapType(typeof(char));
#endif
}
public override Type ExpectedType
{
get { return expectedType; }
}
#if !FEAT_IKVM
public override void Write(object value, ProtoWriter dest)
{
ProtoWriter.WriteUInt16((ushort) (char) value, dest);
}
public override object Read(object value, ProtoReader source)
{
Helpers.DebugAssert(value == null); // since replaces
return (char) source.ReadUInt16();
}
#endif
// no need for any special IL here; ushort and char are
// interchangeable as long as there is no boxing/unboxing
}
}
#endif

Some files were not shown because too many files have changed in this diff Show More