[+] 合理化目录结构 精简非必要插件如确定性物理库以及Recast插件。

[+] 合理化目录结构 精简非必要插件如确定性物理库以及Recast插件。
This commit is contained in:
ALEXTANG
2023-07-25 14:34:05 +08:00
parent f8056aef32
commit 9babc0ba85
260 changed files with 1 additions and 84418 deletions

View File

@@ -4,7 +4,6 @@ using MongoDB.Bson;
using MongoDB.Bson.IO;
using MongoDB.Bson.Serialization;
using MongoDB.Bson.Serialization.Conventions;
using TrueSync;
using Unity.Mathematics;
using MongoHelper = TEngine.Core.MongoHelper;
@@ -23,12 +22,6 @@ public sealed class MongoHelper : Singleton<MongoHelper>
RegisterStruct<float3>();
RegisterStruct<float4>();
RegisterStruct<quaternion>();
RegisterStruct<FP>();
RegisterStruct<TSVector>();
RegisterStruct<TSVector2>();
RegisterStruct<TSVector4>();
RegisterStruct<TSQuaternion>();
}
public static void RegisterStruct<T>() where T : struct

View File

@@ -2,8 +2,6 @@
"name": "DotNet",
"rootNamespace": "",
"references": [
"GUID:d020df1f2b63b444e8ca93c0d88597e2",
"GUID:756335c0388f7114790e504ed368ae1d",
"GUID:d8b63aba1907145bea998dd612889d6b",
"GUID:aa06d4cc755c979489c256c1bcca1dfb"
],

View File

@@ -4,7 +4,6 @@
"references": [
"GUID:08c3762f54316454ca6b6fbcb22b40e5",
"GUID:aa06d4cc755c979489c256c1bcca1dfb",
"GUID:d020df1f2b63b444e8ca93c0d88597e2",
"GUID:ecba4a58c7f7a4842b72ce2c77aecf9b",
"GUID:d8b63aba1907145bea998dd612889d6b"
],

View File

@@ -1,8 +0,0 @@
fileFormatVersion: 2
guid: 1c12ef610b8f30c46996cf5250001b11
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,14 +0,0 @@
{
"name": "DotNet.ThirdParty",
"rootNamespace": "",
"references": [],
"includePlatforms": [],
"excludePlatforms": [],
"allowUnsafeCode": true,
"overrideReferences": false,
"precompiledReferences": [],
"autoReferenced": true,
"defineConstraints": [],
"versionDefines": [],
"noEngineReferences": false
}

View File

@@ -1,7 +0,0 @@
fileFormatVersion: 2
guid: d020df1f2b63b444e8ca93c0d88597e2
AssemblyDefinitionImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,8 +0,0 @@
fileFormatVersion: 2
guid: 6962933a8da958249a243c71feddbd6e
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,712 +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 static 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 COREFX
object obj = TryGetUninitializedObjectWithFormatterServices(type);
if (obj != null) return obj;
#endif
#if PLAT_BINARYFORMATTER && !(COREFX || PROFILE259)
return System.Runtime.Serialization.FormatterServices.GetUninitializedObject(type);
#else
throw new NotSupportedException("Constructor-skipping is not supported on this platform");
#endif
}
#if COREFX // this is inspired by DCS: https://github.com/dotnet/corefx/blob/c02d33b18398199f6acc17d375dab154e9a1df66/src/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlFormatReaderGenerator.cs#L854-L894
static Func<Type, object> getUninitializedObject;
static internal object TryGetUninitializedObjectWithFormatterServices(Type type)
{
if (getUninitializedObject == null)
{
try {
var formatterServiceType = typeof(string).GetTypeInfo().Assembly.GetType("System.Runtime.Serialization.FormatterServices");
if (formatterServiceType == null)
{
// fallback for .Net Core 3.0
var formatterAssembly = Assembly.Load(new AssemblyName("System.Runtime.Serialization.Formatters"));
formatterServiceType = formatterAssembly.GetType("System.Runtime.Serialization.FormatterServices");
}
MethodInfo method = formatterServiceType?.GetMethod("GetUninitializedObject", BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static);
if (method != null)
{
getUninitializedObject = (Func<Type, object>)method.CreateDelegate(typeof(Func<Type, object>));
}
}
catch { /* best efforts only */ }
if(getUninitializedObject == null) getUninitializedObject = x => null;
}
return getUninitializedObject(type);
}
#endif
const int FieldTimeSpanValue = 0x01, FieldTimeSpanScale = 0x02, FieldTimeSpanKind = 0x03;
internal static readonly DateTime[] EpochOrigin = {
new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Unspecified),
new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc),
new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Local)
};
/// <summary>
/// The default value for dates that are following google.protobuf.Timestamp semantics
/// </summary>
private static readonly DateTime TimestampEpoch = EpochOrigin[(int)DateTimeKind.Utc];
/// <summary>
/// Writes a TimeSpan to a protobuf stream using protobuf-net's own representation, bcl.TimeSpan
/// </summary>
public static void WriteTimeSpan(TimeSpan timeSpan, ProtoWriter dest)
{
WriteTimeSpanImpl(timeSpan, dest, DateTimeKind.Unspecified);
}
private static void WriteTimeSpanImpl(TimeSpan timeSpan, ProtoWriter dest, DateTimeKind kind)
{
if (dest == null) throw new ArgumentNullException(nameof(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);
}
if (kind != DateTimeKind.Unspecified)
{
ProtoWriter.WriteFieldHeader(FieldTimeSpanKind, WireType.Variant, dest);
ProtoWriter.WriteInt32((int)kind, 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 using protobuf-net's own representation, bcl.TimeSpan
/// </summary>
public static TimeSpan ReadTimeSpan(ProtoReader source)
{
long ticks = ReadTimeSpanTicks(source, out DateTimeKind kind);
if (ticks == long.MinValue) return TimeSpan.MinValue;
if (ticks == long.MaxValue) return TimeSpan.MaxValue;
return TimeSpan.FromTicks(ticks);
}
/// <summary>
/// Parses a TimeSpan from a protobuf stream using the standardized format, google.protobuf.Duration
/// </summary>
public static TimeSpan ReadDuration(ProtoReader source)
{
long seconds = 0;
int nanos = 0;
SubItemToken token = ProtoReader.StartSubItem(source);
int fieldNumber;
while ((fieldNumber = source.ReadFieldHeader()) > 0)
{
switch (fieldNumber)
{
case 1:
seconds = source.ReadInt64();
break;
case 2:
nanos = source.ReadInt32();
break;
default:
source.SkipField();
break;
}
}
ProtoReader.EndSubItem(token, source);
return FromDurationSeconds(seconds, nanos);
}
/// <summary>
/// Writes a TimeSpan to a protobuf stream using the standardized format, google.protobuf.Duration
/// </summary>
public static void WriteDuration(TimeSpan value, ProtoWriter dest)
{
var seconds = ToDurationSeconds(value, out int nanos);
WriteSecondsNanos(seconds, nanos, dest);
}
private static void WriteSecondsNanos(long seconds, int nanos, ProtoWriter dest)
{
SubItemToken token = ProtoWriter.StartSubItem(null, dest);
if (seconds != 0)
{
ProtoWriter.WriteFieldHeader(1, WireType.Variant, dest);
ProtoWriter.WriteInt64(seconds, dest);
}
if (nanos != 0)
{
ProtoWriter.WriteFieldHeader(2, WireType.Variant, dest);
ProtoWriter.WriteInt32(nanos, dest);
}
ProtoWriter.EndSubItem(token, dest);
}
/// <summary>
/// Parses a DateTime from a protobuf stream using the standardized format, google.protobuf.Timestamp
/// </summary>
public static DateTime ReadTimestamp(ProtoReader source)
{
// note: DateTime is only defined for just over 0000 to just below 10000;
// TimeSpan has a range of +/- 10,675,199 days === 29k years;
// so we can just use epoch time delta
return TimestampEpoch + ReadDuration(source);
}
/// <summary>
/// Writes a DateTime to a protobuf stream using the standardized format, google.protobuf.Timestamp
/// </summary>
public static void WriteTimestamp(DateTime value, ProtoWriter dest)
{
var seconds = ToDurationSeconds(value - TimestampEpoch, out int nanos);
if (nanos < 0)
{ // from Timestamp.proto:
// "Negative second values with fractions must still have
// non -negative nanos values that count forward in time."
seconds--;
nanos += 1000000000;
}
WriteSecondsNanos(seconds, nanos, dest);
}
static TimeSpan FromDurationSeconds(long seconds, int nanos)
{
long ticks = checked((seconds * TimeSpan.TicksPerSecond)
+ (nanos * TimeSpan.TicksPerMillisecond) / 1000000);
return TimeSpan.FromTicks(ticks);
}
static long ToDurationSeconds(TimeSpan value, out int nanos)
{
nanos = (int)(((value.Ticks % TimeSpan.TicksPerSecond) * 1000000)
/ TimeSpan.TicksPerMillisecond);
return value.Ticks / TimeSpan.TicksPerSecond;
}
/// <summary>
/// Parses a DateTime from a protobuf stream
/// </summary>
public static DateTime ReadDateTime(ProtoReader source)
{
long ticks = ReadTimeSpanTicks(source, out DateTimeKind kind);
if (ticks == long.MinValue) return DateTime.MinValue;
if (ticks == long.MaxValue) return DateTime.MaxValue;
return EpochOrigin[(int)kind].AddTicks(ticks);
}
/// <summary>
/// Writes a DateTime to a protobuf stream, excluding the <c>Kind</c>
/// </summary>
public static void WriteDateTime(DateTime value, ProtoWriter dest)
{
WriteDateTimeImpl(value, dest, false);
}
/// <summary>
/// Writes a DateTime to a protobuf stream, including the <c>Kind</c>
/// </summary>
public static void WriteDateTimeWithKind(DateTime value, ProtoWriter dest)
{
WriteDateTimeImpl(value, dest, true);
}
private static void WriteDateTimeImpl(DateTime value, ProtoWriter dest, bool includeKind)
{
if (dest == null) throw new ArgumentNullException(nameof(dest));
TimeSpan delta;
switch (dest.WireType)
{
case WireType.StartGroup:
case WireType.String:
if (value == DateTime.MaxValue)
{
delta = TimeSpan.MaxValue;
includeKind = false;
}
else if (value == DateTime.MinValue)
{
delta = TimeSpan.MinValue;
includeKind = false;
}
else
{
delta = value - EpochOrigin[0];
}
break;
default:
delta = value - EpochOrigin[0];
break;
}
WriteTimeSpanImpl(delta, dest, includeKind ? value.Kind : DateTimeKind.Unspecified);
}
private static long ReadTimeSpanTicks(ProtoReader source, out DateTimeKind kind)
{
kind = DateTimeKind.Unspecified;
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;
case FieldTimeSpanKind:
kind = (DateTimeKind)source.ReadInt32();
switch (kind)
{
case DateTimeKind.Unspecified:
case DateTimeKind.Utc:
case DateTimeKind.Local:
break; // fine
default:
throw new ProtoException("Invalid date/time kind: " + kind.ToString());
}
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());
}
}
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);
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);
}
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)
{
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;
}
/// <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 (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)
{
int objectKey = dest.NetCache.AddObjectKey(value, out bool existing);
ProtoWriter.WriteFieldHeader(existing ? FieldExistingObjectKey : FieldNewObjectKey, WireType.Variant, dest);
ProtoWriter.WriteInt32(objectKey, dest);
if (existing)
{
writeObject = false;
}
}
if (writeObject)
{
if (dynamicType)
{
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 bool 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);
}
}
}

View File

@@ -1,11 +0,0 @@
fileFormatVersion: 2
guid: 5072fbed211eb9f43a3cd2805dd75ef7
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,78 +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, IExtensionResettable
{
private byte[] buffer;
void IExtensionResettable.Reset()
{
buffer = null;
}
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)
{
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];
Buffer.BlockCopy(buffer, 0, tmp, 0, offset);
#if PORTABLE // 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
Buffer.BlockCopy(Helpers.GetBuffer(ms), 0, tmp, offset, len);
#endif
buffer = tmp;
}
}
}
}
Stream IExtension.BeginQuery()
{
return buffer == null ? Stream.Null : new MemoryStream(buffer);
}
void IExtension.EndQuery(Stream stream)
{
using (stream) { } // just clean up
}
}
}

View File

@@ -1,11 +0,0 @@
fileFormatVersion: 2
guid: a9cf66041a027e94892d5014c2b905b3
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,149 +0,0 @@
using System;
namespace ProtoBuf
{
internal sealed class BufferPool
{
internal static void Flush()
{
lock (Pool)
{
for (var i = 0; i < Pool.Length; i++)
Pool[i] = null;
}
}
private BufferPool() { }
private const int POOL_SIZE = 20;
internal const int BUFFER_LENGTH = 1024;
private static readonly CachedBuffer[] Pool = new CachedBuffer[POOL_SIZE];
internal static byte[] GetBuffer() => GetBuffer(BUFFER_LENGTH);
internal static byte[] GetBuffer(int minSize)
{
byte[] cachedBuff = GetCachedBuffer(minSize);
return cachedBuff ?? new byte[minSize];
}
internal static byte[] GetCachedBuffer(int minSize)
{
lock (Pool)
{
var bestIndex = -1;
byte[] bestMatch = null;
for (var i = 0; i < Pool.Length; i++)
{
var buffer = Pool[i];
if (buffer == null || buffer.Size < minSize)
{
continue;
}
if (bestMatch != null && bestMatch.Length < buffer.Size)
{
continue;
}
var tmp = buffer.Buffer;
if (tmp == null)
{
Pool[i] = null;
}
else
{
bestMatch = tmp;
bestIndex = i;
}
}
if (bestIndex >= 0)
{
Pool[bestIndex] = null;
}
return bestMatch;
}
}
/// <remarks>
/// https://docs.microsoft.com/en-us/dotnet/framework/configure-apps/file-schema/runtime/gcallowverylargeobjects-element
/// </remarks>
private const int MaxByteArraySize = int.MaxValue - 56;
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);
int newLength = buffer.Length * 2;
if (newLength < 0)
{
newLength = MaxByteArraySize;
}
if (newLength < toFitAtLeastBytes) newLength = toFitAtLeastBytes;
if (copyBytes == 0)
{
ReleaseBufferToPool(ref buffer);
}
var newBuffer = GetCachedBuffer(toFitAtLeastBytes) ?? new byte[newLength];
if (copyBytes > 0)
{
Buffer.BlockCopy(buffer, copyFromIndex, newBuffer, 0, copyBytes);
ReleaseBufferToPool(ref buffer);
}
buffer = newBuffer;
}
internal static void ReleaseBufferToPool(ref byte[] buffer)
{
if (buffer == null) return;
lock (Pool)
{
var minIndex = 0;
var minSize = int.MaxValue;
for (var i = 0; i < Pool.Length; i++)
{
var tmp = Pool[i];
if (tmp == null || !tmp.IsAlive)
{
minIndex = 0;
break;
}
if (tmp.Size < minSize)
{
minIndex = i;
minSize = tmp.Size;
}
}
Pool[minIndex] = new CachedBuffer(buffer);
}
buffer = null;
}
private class CachedBuffer
{
private readonly WeakReference _reference;
public int Size { get; }
public bool IsAlive => _reference.IsAlive;
public byte[] Buffer => (byte[])_reference.Target;
public CachedBuffer(byte[] buffer)
{
Size = buffer.Length;
_reference = new WeakReference(buffer);
}
}
}
}

View File

@@ -1,11 +0,0 @@
fileFormatVersion: 2
guid: 423b228ed060b91458bc6d4e6aa0f570
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,33 +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 && !PORTABLE && !COREFX && !PROFILE259
[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 && !PORTABLE && !COREFX && !PROFILE259
[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 && !PORTABLE && !COREFX && !PROFILE259
[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 && !PORTABLE && !COREFX && !PROFILE259
[ImmutableObject(true)]
#endif
public sealed class ProtoAfterDeserializationAttribute : Attribute { }
}

View File

@@ -1,11 +0,0 @@
fileFormatVersion: 2
guid: 53de2cb3784c9dd43aa6f30d7df072a4
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,8 +0,0 @@
fileFormatVersion: 2
guid: 2cdd9eb2afa3ed24480a6035f507aad4
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

File diff suppressed because it is too large Load Diff

View File

@@ -1,11 +0,0 @@
fileFormatVersion: 2
guid: a58d20a1d8c7730499ef29a11532d07e
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,7 +0,0 @@
#if FEAT_COMPILER
namespace ProtoBuf.Compiler
{
internal delegate void ProtoSerializer(object value, ProtoWriter dest);
internal delegate object ProtoDeserializer(object value, ProtoReader source);
}
#endif

View File

@@ -1,11 +0,0 @@
fileFormatVersion: 2
guid: 3b923d7ab8e95f740b059ca797596261
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,58 +0,0 @@
#if FEAT_COMPILER
using System;
using System.Reflection.Emit;
namespace ProtoBuf.Compiler
{
internal sealed class Local : IDisposable
{
// public static readonly Local InputValue = new Local(null, null);
private LocalBuilder value;
private readonly Type type;
private CompilerContext ctx;
private Local(LocalBuilder value, Type type)
{
this.value = value;
this.type = type;
}
internal Local(CompilerContext ctx, Type type)
{
this.ctx = ctx;
if (ctx != null) { value = ctx.GetFromPool(type); }
this.type = type;
}
internal LocalBuilder Value => value ?? throw new ObjectDisposedException(GetType().Name);
public Type Type => type;
public Local AsCopy()
{
if (ctx == null) return this; // can re-use if context-free
return new Local(value, this.type);
}
public void Dispose()
{
if (ctx != null)
{
// only *actually* dispose if this is context-bound; note that non-bound
// objects are cheekily re-used, and *must* be left intact agter a "using" etc
ctx.ReleaseToPool(value);
value = null;
ctx = null;
}
}
internal bool IsSame(Local other)
{
if((object)this == (object)other) return true;
object ourVal = value; // use prop to ensure obj-disposed etc
return other != null && ourVal == (object)(other.value);
}
}
}
#endif

View File

@@ -1,11 +0,0 @@
fileFormatVersion: 2
guid: 07d12d9a9b7d45b498e28b7c39bdca01
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,49 +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,
/// <summary>
/// When applied to members of types such as DateTime or TimeSpan, specifies
/// that the "well known" standardized representation should be use; DateTime uses Timestamp,
///
/// </summary>
WellKnown
}
}

View File

@@ -1,11 +0,0 @@
fileFormatVersion: 2
guid: 875f2f7de4b03ff409de70d226359e8f
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,176 +0,0 @@
#if PLAT_BINARYFORMATTER
using System;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
namespace ProtoBuf
{
[Serializable]
public readonly partial struct DiscriminatedUnionObject : ISerializable
{
void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
{
if (Discriminator != default) info.AddValue("d", Discriminator);
if (Object is object) info.AddValue("o", Object);
}
private DiscriminatedUnionObject(SerializationInfo info, StreamingContext context)
{
this = default;
foreach (var field in info)
{
switch (field.Name)
{
case "d": Discriminator = (int)field.Value; break;
case "o": Object = field.Value; break;
}
}
}
}
[Serializable]
public readonly partial struct DiscriminatedUnion128Object : ISerializable
{
[FieldOffset(8)] private readonly long _lo;
[FieldOffset(16)] private readonly long _hi;
void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
{
if (_discriminator != default) info.AddValue("d", _discriminator);
if (_lo != default) info.AddValue("l", _lo);
if (_hi != default) info.AddValue("h", _hi);
if (Object != null) info.AddValue("o", Object);
}
private DiscriminatedUnion128Object(SerializationInfo info, StreamingContext context)
{
this = default;
foreach (var field in info)
{
switch (field.Name)
{
case "d": _discriminator = (int)field.Value; break;
case "l": _lo = (long)field.Value; break;
case "h": _hi = (long)field.Value; break;
case "o": Object = field.Value; break;
}
}
}
}
[Serializable]
public readonly partial struct DiscriminatedUnion128 : ISerializable
{
[FieldOffset(8)] private readonly long _lo;
[FieldOffset(16)] private readonly long _hi;
void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
{
if (_discriminator != default) info.AddValue("d", _discriminator);
if (_lo != default) info.AddValue("l", _lo);
if (_hi != default) info.AddValue("h", _hi);
}
private DiscriminatedUnion128(SerializationInfo info, StreamingContext context)
{
this = default;
foreach (var field in info)
{
switch (field.Name)
{
case "d": _discriminator = (int)field.Value; break;
case "l": _lo = (long)field.Value; break;
case "h": _hi = (long)field.Value; break;
}
}
}
}
[Serializable]
public readonly partial struct DiscriminatedUnion64 : ISerializable
{
void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
{
if (_discriminator != default) info.AddValue("d", _discriminator);
if (Int64 != default) info.AddValue("i", Int64);
}
private DiscriminatedUnion64(SerializationInfo info, StreamingContext context)
{
this = default;
foreach (var field in info)
{
switch (field.Name)
{
case "d": _discriminator = (int)field.Value; break;
case "i": Int64 = (long)field.Value; break;
}
}
}
}
[Serializable]
public readonly partial struct DiscriminatedUnion64Object : ISerializable
{
void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
{
if (_discriminator != default) info.AddValue("d", _discriminator);
if (Int64 != default) info.AddValue("i", Int64);
if (Object is object) info.AddValue("o", Object);
}
private DiscriminatedUnion64Object(SerializationInfo info, StreamingContext context)
{
this = default;
foreach (var field in info)
{
switch (field.Name)
{
case "d": _discriminator = (int)field.Value; break;
case "i": Int64 = (long)field.Value; break;
case "o": Object = field.Value; break;
}
}
}
}
[Serializable]
public readonly partial struct DiscriminatedUnion32 : ISerializable
{
void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
{
if (_discriminator != default) info.AddValue("d", _discriminator);
if (Int32 != default) info.AddValue("i", Int32);
}
private DiscriminatedUnion32(SerializationInfo info, StreamingContext context)
{
this = default;
foreach (var field in info)
{
switch (field.Name)
{
case "d": _discriminator = (int)field.Value; break;
case "i": Int32 = (int)field.Value; break;
}
}
}
}
[Serializable]
public readonly partial struct DiscriminatedUnion32Object : ISerializable
{
void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
{
if (_discriminator != default) info.AddValue("d", _discriminator);
if (Int32 != default) info.AddValue("i", Int32);
if (Object is object) info.AddValue("o", Object);
}
private DiscriminatedUnion32Object(SerializationInfo info, StreamingContext context)
{
this = default;
foreach (var field in info)
{
switch (field.Name)
{
case "d": _discriminator = (int)field.Value; break;
case "i": Int32 = (int)field.Value; break;
case "o": Object = field.Value; break;
}
}
}
}
}
#endif

View File

@@ -1,11 +0,0 @@
fileFormatVersion: 2
guid: 7a3aeec9c8a4c734e9ad022627502d1d
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,416 +0,0 @@
using System;
using System.Runtime.InteropServices;
namespace ProtoBuf
{
/// <summary>Represent multiple types as a union; this is used as part of OneOf -
/// note that it is the caller's responsbility to only read/write the value as the same type</summary>
public readonly partial struct DiscriminatedUnionObject
{
/// <summary>The value typed as Object</summary>
public readonly object Object;
/// <summary>Indicates whether the specified discriminator is assigned</summary>
public bool Is(int discriminator) => Discriminator == discriminator;
/// <summary>Create a new discriminated union value</summary>
public DiscriminatedUnionObject(int discriminator, object value)
{
Discriminator = discriminator;
Object = value;
}
/// <summary>Reset a value if the specified discriminator is assigned</summary>
public static void Reset(ref DiscriminatedUnionObject value, int discriminator)
{
if (value.Discriminator == discriminator) value = default;
}
/// <summary>The discriminator value</summary>
public int Discriminator { get; }
}
/// <summary>Represent multiple types as a union; this is used as part of OneOf -
/// note that it is the caller's responsbility to only read/write the value as the same type</summary>
[StructLayout(LayoutKind.Explicit)]
public readonly partial struct DiscriminatedUnion64
{
#if !FEAT_SAFE
unsafe static DiscriminatedUnion64()
{
if (sizeof(DateTime) > 8) throw new InvalidOperationException(nameof(DateTime) + " was unexpectedly too big for " + nameof(DiscriminatedUnion64));
if (sizeof(TimeSpan) > 8) throw new InvalidOperationException(nameof(TimeSpan) + " was unexpectedly too big for " + nameof(DiscriminatedUnion64));
}
#endif
[FieldOffset(0)] private readonly int _discriminator; // note that we can't pack further because Object needs x8 alignment/padding on x64
/// <summary>The value typed as Int64</summary>
[FieldOffset(8)] public readonly long Int64;
/// <summary>The value typed as UInt64</summary>
[FieldOffset(8)] public readonly ulong UInt64;
/// <summary>The value typed as Int32</summary>
[FieldOffset(8)] public readonly int Int32;
/// <summary>The value typed as UInt32</summary>
[FieldOffset(8)] public readonly uint UInt32;
/// <summary>The value typed as Boolean</summary>
[FieldOffset(8)] public readonly bool Boolean;
/// <summary>The value typed as Single</summary>
[FieldOffset(8)] public readonly float Single;
/// <summary>The value typed as Double</summary>
[FieldOffset(8)] public readonly double Double;
/// <summary>The value typed as DateTime</summary>
[FieldOffset(8)] public readonly DateTime DateTime;
/// <summary>The value typed as TimeSpan</summary>
[FieldOffset(8)] public readonly TimeSpan TimeSpan;
private DiscriminatedUnion64(int discriminator) : this()
{
_discriminator = discriminator;
}
/// <summary>Indicates whether the specified discriminator is assigned</summary>
public bool Is(int discriminator) => _discriminator == discriminator;
/// <summary>Create a new discriminated union value</summary>
public DiscriminatedUnion64(int discriminator, long value) : this(discriminator) { Int64 = value; }
/// <summary>Create a new discriminated union value</summary>
public DiscriminatedUnion64(int discriminator, int value) : this(discriminator) { Int32 = value; }
/// <summary>Create a new discriminated union value</summary>
public DiscriminatedUnion64(int discriminator, ulong value) : this(discriminator) { UInt64 = value; }
/// <summary>Create a new discriminated union value</summary>
public DiscriminatedUnion64(int discriminator, uint value) : this(discriminator) { UInt32 = value; }
/// <summary>Create a new discriminated union value</summary>
public DiscriminatedUnion64(int discriminator, float value) : this(discriminator) { Single = value; }
/// <summary>Create a new discriminated union value</summary>
public DiscriminatedUnion64(int discriminator, double value) : this(discriminator) { Double = value; }
/// <summary>Create a new discriminated union value</summary>
public DiscriminatedUnion64(int discriminator, bool value) : this(discriminator) { Boolean = value; }
/// <summary>Create a new discriminated union value</summary>
public DiscriminatedUnion64(int discriminator, DateTime? value) : this(value.HasValue ? discriminator: 0) { DateTime = value.GetValueOrDefault(); }
/// <summary>Create a new discriminated union value</summary>
public DiscriminatedUnion64(int discriminator, TimeSpan? value) : this(value.HasValue ? discriminator : 0) { TimeSpan = value.GetValueOrDefault(); }
/// <summary>Reset a value if the specified discriminator is assigned</summary>
public static void Reset(ref DiscriminatedUnion64 value, int discriminator)
{
if (value.Discriminator == discriminator) value = default;
}
/// <summary>The discriminator value</summary>
public int Discriminator => _discriminator;
}
/// <summary>Represent multiple types as a union; this is used as part of OneOf -
/// note that it is the caller's responsbility to only read/write the value as the same type</summary>
[StructLayout(LayoutKind.Explicit)]
public readonly partial struct DiscriminatedUnion128Object
{
#if !FEAT_SAFE
unsafe static DiscriminatedUnion128Object()
{
if (sizeof(DateTime) > 16) throw new InvalidOperationException(nameof(DateTime) + " was unexpectedly too big for " + nameof(DiscriminatedUnion128Object));
if (sizeof(TimeSpan) > 16) throw new InvalidOperationException(nameof(TimeSpan) + " was unexpectedly too big for " + nameof(DiscriminatedUnion128Object));
if (sizeof(Guid) > 16) throw new InvalidOperationException(nameof(Guid) + " was unexpectedly too big for " + nameof(DiscriminatedUnion128Object));
}
#endif
[FieldOffset(0)] private readonly int _discriminator; // note that we can't pack further because Object needs x8 alignment/padding on x64
/// <summary>The value typed as Int64</summary>
[FieldOffset(8)] public readonly long Int64;
/// <summary>The value typed as UInt64</summary>
[FieldOffset(8)] public readonly ulong UInt64;
/// <summary>The value typed as Int32</summary>
[FieldOffset(8)] public readonly int Int32;
/// <summary>The value typed as UInt32</summary>
[FieldOffset(8)] public readonly uint UInt32;
/// <summary>The value typed as Boolean</summary>
[FieldOffset(8)] public readonly bool Boolean;
/// <summary>The value typed as Single</summary>
[FieldOffset(8)] public readonly float Single;
/// <summary>The value typed as Double</summary>
[FieldOffset(8)] public readonly double Double;
/// <summary>The value typed as DateTime</summary>
[FieldOffset(8)] public readonly DateTime DateTime;
/// <summary>The value typed as TimeSpan</summary>
[FieldOffset(8)] public readonly TimeSpan TimeSpan;
/// <summary>The value typed as Guid</summary>
[FieldOffset(8)] public readonly Guid Guid;
/// <summary>The value typed as Object</summary>
[FieldOffset(24)] public readonly object Object;
private DiscriminatedUnion128Object(int discriminator) : this()
{
_discriminator = discriminator;
}
/// <summary>Indicates whether the specified discriminator is assigned</summary>
public bool Is(int discriminator) => _discriminator == discriminator;
/// <summary>Create a new discriminated union value</summary>
public DiscriminatedUnion128Object(int discriminator, long value) : this(discriminator) { Int64 = value; }
/// <summary>Create a new discriminated union value</summary>
public DiscriminatedUnion128Object(int discriminator, int value) : this(discriminator) { Int32 = value; }
/// <summary>Create a new discriminated union value</summary>
public DiscriminatedUnion128Object(int discriminator, ulong value) : this(discriminator) { UInt64 = value; }
/// <summary>Create a new discriminated union value</summary>
public DiscriminatedUnion128Object(int discriminator, uint value) : this(discriminator) { UInt32 = value; }
/// <summary>Create a new discriminated union value</summary>
public DiscriminatedUnion128Object(int discriminator, float value) : this(discriminator) { Single = value; }
/// <summary>Create a new discriminated union value</summary>
public DiscriminatedUnion128Object(int discriminator, double value) : this(discriminator) { Double = value; }
/// <summary>Create a new discriminated union value</summary>
public DiscriminatedUnion128Object(int discriminator, bool value) : this(discriminator) { Boolean = value; }
/// <summary>Create a new discriminated union value</summary>
public DiscriminatedUnion128Object(int discriminator, object value) : this(value != null ? discriminator : 0) { Object = value; }
/// <summary>Create a new discriminated union value</summary>
public DiscriminatedUnion128Object(int discriminator, DateTime? value) : this(value.HasValue ? discriminator: 0) { DateTime = value.GetValueOrDefault(); }
/// <summary>Create a new discriminated union value</summary>
public DiscriminatedUnion128Object(int discriminator, TimeSpan? value) : this(value.HasValue ? discriminator : 0) { TimeSpan = value.GetValueOrDefault(); }
/// <summary>Create a new discriminated union value</summary>
public DiscriminatedUnion128Object(int discriminator, Guid? value) : this(value.HasValue ? discriminator : 0) { Guid = value.GetValueOrDefault(); }
/// <summary>Reset a value if the specified discriminator is assigned</summary>
public static void Reset(ref DiscriminatedUnion128Object value, int discriminator)
{
if (value.Discriminator == discriminator) value = default;
}
/// <summary>The discriminator value</summary>
public int Discriminator => _discriminator;
}
/// <summary>Represent multiple types as a union; this is used as part of OneOf -
/// note that it is the caller's responsbility to only read/write the value as the same type</summary>
[StructLayout(LayoutKind.Explicit)]
public readonly partial struct DiscriminatedUnion128
{
#if !FEAT_SAFE
unsafe static DiscriminatedUnion128()
{
if (sizeof(DateTime) > 16) throw new InvalidOperationException(nameof(DateTime) + " was unexpectedly too big for " + nameof(DiscriminatedUnion128));
if (sizeof(TimeSpan) > 16) throw new InvalidOperationException(nameof(TimeSpan) + " was unexpectedly too big for " + nameof(DiscriminatedUnion128));
if (sizeof(Guid) > 16) throw new InvalidOperationException(nameof(Guid) + " was unexpectedly too big for " + nameof(DiscriminatedUnion128));
}
#endif
[FieldOffset(0)] private readonly int _discriminator; // note that we can't pack further because Object needs x8 alignment/padding on x64
/// <summary>The value typed as Int64</summary>
[FieldOffset(8)] public readonly long Int64;
/// <summary>The value typed as UInt64</summary>
[FieldOffset(8)] public readonly ulong UInt64;
/// <summary>The value typed as Int32</summary>
[FieldOffset(8)] public readonly int Int32;
/// <summary>The value typed as UInt32</summary>
[FieldOffset(8)] public readonly uint UInt32;
/// <summary>The value typed as Boolean</summary>
[FieldOffset(8)] public readonly bool Boolean;
/// <summary>The value typed as Single</summary>
[FieldOffset(8)] public readonly float Single;
/// <summary>The value typed as Double</summary>
[FieldOffset(8)] public readonly double Double;
/// <summary>The value typed as DateTime</summary>
[FieldOffset(8)] public readonly DateTime DateTime;
/// <summary>The value typed as TimeSpan</summary>
[FieldOffset(8)] public readonly TimeSpan TimeSpan;
/// <summary>The value typed as Guid</summary>
[FieldOffset(8)] public readonly Guid Guid;
private DiscriminatedUnion128(int discriminator) : this()
{
_discriminator = discriminator;
}
/// <summary>Indicates whether the specified discriminator is assigned</summary>
public bool Is(int discriminator) => _discriminator == discriminator;
/// <summary>Create a new discriminated union value</summary>
public DiscriminatedUnion128(int discriminator, long value) : this(discriminator) { Int64 = value; }
/// <summary>Create a new discriminated union value</summary>
public DiscriminatedUnion128(int discriminator, int value) : this(discriminator) { Int32 = value; }
/// <summary>Create a new discriminated union value</summary>
public DiscriminatedUnion128(int discriminator, ulong value) : this(discriminator) { UInt64 = value; }
/// <summary>Create a new discriminated union value</summary>
public DiscriminatedUnion128(int discriminator, uint value) : this(discriminator) { UInt32 = value; }
/// <summary>Create a new discriminated union value</summary>
public DiscriminatedUnion128(int discriminator, float value) : this(discriminator) { Single = value; }
/// <summary>Create a new discriminated union value</summary>
public DiscriminatedUnion128(int discriminator, double value) : this(discriminator) { Double = value; }
/// <summary>Create a new discriminated union value</summary>
public DiscriminatedUnion128(int discriminator, bool value) : this(discriminator) { Boolean = value; }
/// <summary>Create a new discriminated union value</summary>
public DiscriminatedUnion128(int discriminator, DateTime? value) : this(value.HasValue ? discriminator: 0) { DateTime = value.GetValueOrDefault(); }
/// <summary>Create a new discriminated union value</summary>
public DiscriminatedUnion128(int discriminator, TimeSpan? value) : this(value.HasValue ? discriminator : 0) { TimeSpan = value.GetValueOrDefault(); }
/// <summary>Create a new discriminated union value</summary>
public DiscriminatedUnion128(int discriminator, Guid? value) : this(value.HasValue ? discriminator : 0) { Guid = value.GetValueOrDefault(); }
/// <summary>Reset a value if the specified discriminator is assigned</summary>
public static void Reset(ref DiscriminatedUnion128 value, int discriminator)
{
if (value.Discriminator == discriminator) value = default;
}
/// <summary>The discriminator value</summary>
public int Discriminator => _discriminator;
}
/// <summary>Represent multiple types as a union; this is used as part of OneOf -
/// note that it is the caller's responsbility to only read/write the value as the same type</summary>
[StructLayout(LayoutKind.Explicit)]
public readonly partial struct DiscriminatedUnion64Object
{
#if !FEAT_SAFE
unsafe static DiscriminatedUnion64Object()
{
if (sizeof(DateTime) > 8) throw new InvalidOperationException(nameof(DateTime) + " was unexpectedly too big for " + nameof(DiscriminatedUnion64Object));
if (sizeof(TimeSpan) > 8) throw new InvalidOperationException(nameof(TimeSpan) + " was unexpectedly too big for " + nameof(DiscriminatedUnion64Object));
}
#endif
[FieldOffset(0)] private readonly int _discriminator; // note that we can't pack further because Object needs x8 alignment/padding on x64
/// <summary>The value typed as Int64</summary>
[FieldOffset(8)] public readonly long Int64;
/// <summary>The value typed as UInt64</summary>
[FieldOffset(8)] public readonly ulong UInt64;
/// <summary>The value typed as Int32</summary>
[FieldOffset(8)] public readonly int Int32;
/// <summary>The value typed as UInt32</summary>
[FieldOffset(8)] public readonly uint UInt32;
/// <summary>The value typed as Boolean</summary>
[FieldOffset(8)] public readonly bool Boolean;
/// <summary>The value typed as Single</summary>
[FieldOffset(8)] public readonly float Single;
/// <summary>The value typed as Double</summary>
[FieldOffset(8)] public readonly double Double;
/// <summary>The value typed as DateTime</summary>
[FieldOffset(8)] public readonly DateTime DateTime;
/// <summary>The value typed as TimeSpan</summary>
[FieldOffset(8)] public readonly TimeSpan TimeSpan;
/// <summary>The value typed as Object</summary>
[FieldOffset(16)] public readonly object Object;
private DiscriminatedUnion64Object(int discriminator) : this()
{
_discriminator = discriminator;
}
/// <summary>Indicates whether the specified discriminator is assigned</summary>
public bool Is(int discriminator) => _discriminator == discriminator;
/// <summary>Create a new discriminated union value</summary>
public DiscriminatedUnion64Object(int discriminator, long value) : this(discriminator) { Int64 = value; }
/// <summary>Create a new discriminated union value</summary>
public DiscriminatedUnion64Object(int discriminator, int value) : this(discriminator) { Int32 = value; }
/// <summary>Create a new discriminated union value</summary>
public DiscriminatedUnion64Object(int discriminator, ulong value) : this(discriminator) { UInt64 = value; }
/// <summary>Create a new discriminated union value</summary>
public DiscriminatedUnion64Object(int discriminator, uint value) : this(discriminator) { UInt32 = value; }
/// <summary>Create a new discriminated union value</summary>
public DiscriminatedUnion64Object(int discriminator, float value) : this(discriminator) { Single = value; }
/// <summary>Create a new discriminated union value</summary>
public DiscriminatedUnion64Object(int discriminator, double value) : this(discriminator) { Double = value; }
/// <summary>Create a new discriminated union value</summary>
public DiscriminatedUnion64Object(int discriminator, bool value) : this(discriminator) { Boolean = value; }
/// <summary>Create a new discriminated union value</summary>
public DiscriminatedUnion64Object(int discriminator, object value) : this(value != null ? discriminator : 0) { Object = value; }
/// <summary>Create a new discriminated union value</summary>
public DiscriminatedUnion64Object(int discriminator, DateTime? value) : this(value.HasValue ? discriminator: 0) { DateTime = value.GetValueOrDefault(); }
/// <summary>Create a new discriminated union value</summary>
public DiscriminatedUnion64Object(int discriminator, TimeSpan? value) : this(value.HasValue ? discriminator : 0) { TimeSpan = value.GetValueOrDefault(); }
/// <summary>Reset a value if the specified discriminator is assigned</summary>
public static void Reset(ref DiscriminatedUnion64Object value, int discriminator)
{
if (value.Discriminator == discriminator) value = default;
}
/// <summary>The discriminator value</summary>
public int Discriminator => _discriminator;
}
/// <summary>Represent multiple types as a union; this is used as part of OneOf -
/// note that it is the caller's responsbility to only read/write the value as the same type</summary>
[StructLayout(LayoutKind.Explicit)]
public readonly partial struct DiscriminatedUnion32
{
[FieldOffset(0)] private readonly int _discriminator;
/// <summary>The value typed as Int32</summary>
[FieldOffset(4)] public readonly int Int32;
/// <summary>The value typed as UInt32</summary>
[FieldOffset(4)] public readonly uint UInt32;
/// <summary>The value typed as Boolean</summary>
[FieldOffset(4)] public readonly bool Boolean;
/// <summary>The value typed as Single</summary>
[FieldOffset(4)] public readonly float Single;
private DiscriminatedUnion32(int discriminator) : this()
{
_discriminator = discriminator;
}
/// <summary>Indicates whether the specified discriminator is assigned</summary>
public bool Is(int discriminator) => _discriminator == discriminator;
/// <summary>Create a new discriminated union value</summary>
public DiscriminatedUnion32(int discriminator, int value) : this(discriminator) { Int32 = value; }
/// <summary>Create a new discriminated union value</summary>
public DiscriminatedUnion32(int discriminator, uint value) : this(discriminator) { UInt32 = value; }
/// <summary>Create a new discriminated union value</summary>
public DiscriminatedUnion32(int discriminator, float value) : this(discriminator) { Single = value; }
/// <summary>Create a new discriminated union value</summary>
public DiscriminatedUnion32(int discriminator, bool value) : this(discriminator) { Boolean = value; }
/// <summary>Reset a value if the specified discriminator is assigned</summary>
public static void Reset(ref DiscriminatedUnion32 value, int discriminator)
{
if (value.Discriminator == discriminator) value = default;
}
/// <summary>The discriminator value</summary>
public int Discriminator => _discriminator;
}
/// <summary>Represent multiple types as a union; this is used as part of OneOf -
/// note that it is the caller's responsbility to only read/write the value as the same type</summary>
[StructLayout(LayoutKind.Explicit)]
public readonly partial struct DiscriminatedUnion32Object
{
[FieldOffset(0)] private readonly int _discriminator;
/// <summary>The value typed as Int32</summary>
[FieldOffset(4)] public readonly int Int32;
/// <summary>The value typed as UInt32</summary>
[FieldOffset(4)] public readonly uint UInt32;
/// <summary>The value typed as Boolean</summary>
[FieldOffset(4)] public readonly bool Boolean;
/// <summary>The value typed as Single</summary>
[FieldOffset(4)] public readonly float Single;
/// <summary>The value typed as Object</summary>
[FieldOffset(8)] public readonly object Object;
private DiscriminatedUnion32Object(int discriminator) : this()
{
_discriminator = discriminator;
}
/// <summary>Indicates whether the specified discriminator is assigned</summary>
public bool Is(int discriminator) => _discriminator == discriminator;
/// <summary>Create a new discriminated union value</summary>
public DiscriminatedUnion32Object(int discriminator, int value) : this(discriminator) { Int32 = value; }
/// <summary>Create a new discriminated union value</summary>
public DiscriminatedUnion32Object(int discriminator, uint value) : this(discriminator) { UInt32 = value; }
/// <summary>Create a new discriminated union value</summary>
public DiscriminatedUnion32Object(int discriminator, float value) : this(discriminator) { Single = value; }
/// <summary>Create a new discriminated union value</summary>
public DiscriminatedUnion32Object(int discriminator, bool value) : this(discriminator) { Boolean = value; }
/// <summary>Create a new discriminated union value</summary>
public DiscriminatedUnion32Object(int discriminator, object value) : this(value != null ? discriminator : 0) { Object = value; }
/// <summary>Reset a value if the specified discriminator is assigned</summary>
public static void Reset(ref DiscriminatedUnion32Object value, int discriminator)
{
if (value.Discriminator == discriminator) value = default;
}
/// <summary>The discriminator value</summary>
public int Discriminator => _discriminator;
}
}

View File

@@ -1,11 +0,0 @@
fileFormatVersion: 2
guid: ab51817e163a1144bb8518368ba0a465
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,284 +0,0 @@
using System;
using System.Collections.Generic;
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
/// <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)
{
TryGetValue<TValue>(instance, tag, format, out TValue 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;
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, 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, 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,11 +0,0 @@
fileFormatVersion: 2
guid: fc24b62dbd0b19642bce397e2b061aa0
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,118 +0,0 @@
using System;
using System.Collections;
using System.Collections.Generic;
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
/// across classes
/// </summary>
internal static class ExtensibleUtil
{
#if !NO_RUNTIME
/// <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 (instance == null) throw new ArgumentNullException(nameof(instance));
if (tag <= 0) throw new ArgumentOutOfRangeException(nameof(tag));
IExtension extn = instance.GetExtensionObject(false);
if (extn == null)
{
yield break;
}
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, true, false, false, null) && value != null)
{
if (!singleton)
{
yield return value;
value = null; // fresh item each time
}
}
if (singleton && value != null)
{
yield return value;
}
}
finally
{
ProtoReader.Recycle(reader);
extn.EndQuery(stream);
}
}
internal static void AppendExtendValue(TypeModel model, IExtensible instance, int tag, DataFormat format, object value)
{
if (instance == null) throw new ArgumentNullException(nameof(instance));
if (value == null) throw new ArgumentNullException(nameof(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 = ProtoWriter.Create(stream, model, null))
{
model.TrySerializeAuxiliaryType(writer, null, format, tag, value, false, null);
writer.Close();
}
commit = true;
}
finally
{
extn.EndAppend(stream, commit);
}
}
// /// <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);
// }
}
}

View File

@@ -1,11 +0,0 @@
fileFormatVersion: 2
guid: dc71d3f5e8f25ad41bb04ea933cee56e
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,11 +0,0 @@
fileFormatVersion: 2
guid: c110f96e5d6da4f498bcb6d5fa673be7
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,638 +0,0 @@

using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text;
#if COREFX
using System.Linq;
#endif
#if PROFILE259
using System.Reflection;
using System.Linq;
#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 StringBuilder AppendLine(StringBuilder builder)
{
return builder.AppendLine();
}
[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
System.Diagnostics.Debug.WriteLine(message);
#endif
}
[System.Diagnostics.Conditional("TRACE")]
public static void TraceWriteLine(string message)
{
#if TRACE
#if CF2 || PORTABLE || COREFX || PROFILE259
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)
{
System.Diagnostics.Debug.Assert(false, message);
}
#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 (!condition && System.Diagnostics.Debugger.IsAttached) System.Diagnostics.Debugger.Break();
System.Diagnostics.Debug.Assert(condition);
#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
#if COREFX
internal static MemberInfo GetInstanceMember(TypeInfo declaringType, string name)
{
var members = declaringType.AsType().GetMember(name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
switch(members.Length)
{
case 0: return null;
case 1: return members[0];
default: throw new AmbiguousMatchException(name);
}
}
internal static MethodInfo GetInstanceMethod(Type declaringType, string name)
{
foreach (MethodInfo method in declaringType.GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic))
{
if (method.Name == name) return method;
}
return null;
}
internal static MethodInfo GetInstanceMethod(TypeInfo declaringType, string name)
{
return GetInstanceMethod(declaringType.AsType(), name); ;
}
internal static MethodInfo GetStaticMethod(Type declaringType, string name)
{
foreach (MethodInfo method in declaringType.GetMethods(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic))
{
if (method.Name == name) return method;
}
return null;
}
internal static MethodInfo GetStaticMethod(TypeInfo declaringType, string name)
{
return GetStaticMethod(declaringType.AsType(), name);
}
internal static MethodInfo GetStaticMethod(Type declaringType, string name, Type[] parameterTypes)
{
foreach(MethodInfo method in declaringType.GetMethods(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic))
{
if (method.Name == name && IsMatch(method.GetParameters(), parameterTypes)) return method;
}
return null;
}
internal static MethodInfo GetInstanceMethod(Type declaringType, string name, Type[] parameterTypes)
{
foreach (MethodInfo method in declaringType.GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic))
{
if (method.Name == name && IsMatch(method.GetParameters(), parameterTypes)) return method;
}
return null;
}
internal static MethodInfo GetInstanceMethod(TypeInfo declaringType, string name, Type[] types)
{
return GetInstanceMethod(declaringType.AsType(), name, types);
}
#elif PROFILE259
internal static MemberInfo GetInstanceMember(TypeInfo declaringType, string name)
{
IEnumerable<MemberInfo> members = declaringType.DeclaredMembers;
IList<MemberInfo> found = new List<MemberInfo>();
foreach (MemberInfo member in members)
{
if (member.Name.Equals(name))
{
found.Add(member);
}
}
switch (found.Count)
{
case 0: return null;
case 1: return found.First();
default: throw new AmbiguousMatchException(name);
}
}
internal static MethodInfo GetInstanceMethod(Type declaringType, string name)
{
var methods = declaringType.GetRuntimeMethods();
foreach (MethodInfo method in methods)
{
if (method.Name == name)
{
return method;
}
}
return null;
}
internal static MethodInfo GetInstanceMethod(TypeInfo declaringType, string name)
{
return GetInstanceMethod(declaringType.AsType(), name); ;
}
internal static MethodInfo GetStaticMethod(Type declaringType, string name)
{
var methods = declaringType.GetRuntimeMethods();
foreach (MethodInfo method in methods)
{
if (method.Name == name)
{
return method;
}
}
return null;
}
internal static MethodInfo GetStaticMethod(TypeInfo declaringType, string name)
{
return GetStaticMethod(declaringType.AsType(), name);
}
internal static MethodInfo GetStaticMethod(Type declaringType, string name, Type[] parameterTypes)
{
var methods = declaringType.GetRuntimeMethods();
foreach (MethodInfo method in methods)
{
if (method.Name == name &&
IsMatch(method.GetParameters(), parameterTypes))
{
return method;
}
}
return null;
}
internal static MethodInfo GetInstanceMethod(Type declaringType, string name, Type[] parameterTypes)
{
var methods = declaringType.GetRuntimeMethods();
foreach (MethodInfo method in methods)
{
if (method.Name == name &&
IsMatch(method.GetParameters(), parameterTypes))
{
return method;
}
}
return null;
}
internal static MethodInfo GetInstanceMethod(TypeInfo declaringType, string name, Type[] types)
{
return GetInstanceMethod(declaringType.AsType(), name, types);
}
#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 GetStaticMethod(Type declaringType, string name, Type[] parameterTypes)
{
#if PORTABLE
foreach (MethodInfo method in declaringType.GetMethods(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic))
{
if (method.Name == name && IsMatch(method.GetParameters(), parameterTypes)) return method;
}
return null;
#else
return declaringType.GetMethod(name, BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic, null, parameterTypes, null);
#endif
}
internal static MethodInfo GetInstanceMethod(Type declaringType, string name, Type[] types)
{
if (types == null) types = EmptyTypes;
#if PORTABLE || COREFX
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 COREFX || PROFILE259
return type.GetTypeInfo().IsSubclassOf(baseClass);
#else
return type.IsSubclassOf(baseClass);
#endif
}
public readonly static Type[] EmptyTypes =
#if PORTABLE || CF2 || CF35 || PROFILE259
new Type[0];
#else
Type.EmptyTypes;
#endif
#if COREFX || PROFILE259
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(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
public static ProtoTypeCode GetTypeCode(Type type)
{
#if COREFX || PROFILE259
if (IsEnum(type))
{
type = Enum.GetUnderlyingType(type);
}
int idx = Array.IndexOf<Type>(knownTypes, type);
if (idx >= 0) return knownCodes[idx];
return type == null ? ProtoTypeCode.Empty : ProtoTypeCode.Unknown;
#else
TypeCode code = 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 PORTABLE
// In PCLs, the Uri type may not match (WinRT uses Internal/Uri, .Net uses System/Uri), so match on the full name instead
if (type.FullName == typeof(Uri).FullName) return ProtoTypeCode.Uri;
#endif
if (type == typeof(byte[])) return ProtoTypeCode.ByteArray;
if (type == typeof(Type)) return ProtoTypeCode.Type;
return ProtoTypeCode.Unknown;
#endif
}
internal static Type GetUnderlyingType(Type type)
{
return Nullable.GetUnderlyingType(type);
}
internal static bool IsValueType(Type type)
{
#if COREFX || PROFILE259
return type.GetTypeInfo().IsValueType;
#else
return type.IsValueType;
#endif
}
internal static bool IsSealed(Type type)
{
#if COREFX || PROFILE259
return type.GetTypeInfo().IsSealed;
#else
return type.IsSealed;
#endif
}
internal static bool IsClass(Type type)
{
#if COREFX || PROFILE259
return type.GetTypeInfo().IsClass;
#else
return type.IsClass;
#endif
}
internal static bool IsEnum(Type type)
{
#if COREFX || PROFILE259
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 COREFX || PROFILE259
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 COREFX || PROFILE259
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 COREFX || PORTABLE || PROFILE259
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;
}
#endif
#if COREFX || PROFILE259
internal static ConstructorInfo GetConstructor(Type type, Type[] parameterTypes, bool nonPublic)
{
return GetConstructor(type.GetTypeInfo(), parameterTypes, nonPublic);
}
internal static ConstructorInfo GetConstructor(TypeInfo type, Type[] parameterTypes, bool nonPublic)
{
return GetConstructors(type, nonPublic).SingleOrDefault(ctor => IsMatch(ctor.GetParameters(), parameterTypes));
}
internal static ConstructorInfo[] GetConstructors(TypeInfo typeInfo, bool nonPublic)
{
return typeInfo.DeclaredConstructors.Where(c => !c.IsStatic && ((!nonPublic && c.IsPublic) || nonPublic)).ToArray();
}
internal static PropertyInfo GetProperty(Type type, string name, bool nonPublic)
{
return GetProperty(type.GetTypeInfo(), name, nonPublic);
}
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 || COREFX
// 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)
{
return Enum.Parse(type, value, true);
}
internal static MemberInfo[] GetInstanceFieldsAndProperties(Type type, bool publicOnly)
{
#if PROFILE259
var members = new 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 PORTABLE || COREFX || PROFILE259
if (member is PropertyInfo prop) return prop.PropertyType;
FieldInfo fld = member as FieldInfo;
return 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 PROFILE259
return target.GetTypeInfo().IsAssignableFrom(type.GetTypeInfo());
#else
return target.IsAssignableFrom(type);
#endif
}
internal static Assembly GetAssembly(Type type)
{
#if COREFX || PROFILE259
return type.GetTypeInfo().Assembly;
#else
return type.Assembly;
#endif
}
internal static byte[] GetBuffer(MemoryStream ms)
{
#if COREFX
if(!ms.TryGetBuffer(out var segment))
{
throw new InvalidOperationException("Unable to obtain underlying MemoryStream buffer");
} else if(segment.Offset != 0)
{
throw new InvalidOperationException("Underlying MemoryStream buffer was not zero-offset");
} else
{
return segment.Array;
}
#elif PORTABLE || PROFILE259
return ms.ToArray();
#else
return ms.GetBuffer();
#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,11 +0,0 @@
fileFormatVersion: 2
guid: 227f762ea287cdf42a9293ea6c481ff8
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,23 +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,11 +0,0 @@
fileFormatVersion: 2
guid: b9cd5092c5d6d9d4299fc0c88ebb9390
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,58 +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();
}
/// <summary>
/// Provides the ability to remove all existing extension data
/// </summary>
public interface IExtensionResettable : IExtension
{
/// <summary>
/// Remove all existing extension data
/// </summary>
void Reset();
}
}

View File

@@ -1,11 +0,0 @@
fileFormatVersion: 2
guid: 8018fb363175787478148842225e7d16
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,13 +0,0 @@
namespace ProtoBuf
{
/// <summary>
/// Represents the ability to deserialize values from an input of type <typeparamref name="TInput"/>
/// </summary>
public interface IProtoInput<TInput>
{
/// <summary>
/// Deserialize a value from the input
/// </summary>
T Deserialize<T>(TInput source, T value = default, object userState = null);
}
}

View File

@@ -1,11 +0,0 @@
fileFormatVersion: 2
guid: a6514bacfd3143a49a027f15434586f7
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,55 +0,0 @@
using System;
namespace ProtoBuf
{
/// <summary>
/// Represents the ability to serialize values to an output of type <typeparamref name="TOutput"/>
/// </summary>
public interface IProtoOutput<TOutput>
{
/// <summary>
/// Serialize the provided value
/// </summary>
void Serialize<T>(TOutput destination, T value, object userState = null);
}
/// <summary>
/// Represents the ability to serialize values to an output of type <typeparamref name="TOutput"/>
/// with pre-computation of the length
/// </summary>
public interface IMeasuredProtoOutput<TOutput> : IProtoOutput<TOutput>
{
/// <summary>
/// Measure the length of a value in advance of serialization
/// </summary>
MeasureState<T> Measure<T>(T value, object userState = null);
/// <summary>
/// Serialize the previously measured value
/// </summary>
void Serialize<T>(MeasureState<T> measured, TOutput destination);
}
/// <summary>
/// Represents the outcome of computing the length of an object; since this may have required computing lengths
/// for multiple objects, some metadata is retained so that a subsequent serialize operation using
/// this instance can re-use the previously calculated lengths. If the object state changes between the
/// measure and serialize operations, the behavior is undefined.
/// </summary>
public struct MeasureState<T> : IDisposable
// note: 2.4.* does not actually implement this API;
// it only advertises it for 3.* capability/feature-testing, i.e.
// callers can check whether a model implements
// IMeasuredProtoOutput<Foo>, and *work from that*
{
/// <summary>
/// Releases all resources associated with this value
/// </summary>
public void Dispose() => throw new NotImplementedException();
/// <summary>
/// Gets the calculated length of this serialize operation, in bytes
/// </summary>
public long Length => throw new NotImplementedException();
}
}

View File

@@ -1,11 +0,0 @@
fileFormatVersion: 2
guid: 17c52d90924d69d4aaf31925ea2c90bf
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,29 +0,0 @@
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,11 +0,0 @@
fileFormatVersion: 2
guid: b838f9e3c6536bc438e7c31f73c49160
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,44 +0,0 @@
//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);
// }
// }
//}

View File

@@ -1,11 +0,0 @@
fileFormatVersion: 2
guid: b6221476e2339494cb5ee2bdc10ffd81
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,8 +0,0 @@
fileFormatVersion: 2
guid: a70a85c13dddce74d9a6395c440c9156
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,108 +0,0 @@
#if !NO_RUNTIME
using System;
using System.Reflection;
namespace ProtoBuf.Meta
{
internal abstract class AttributeMap
{
#if DEBUG
[Obsolete("Please use AttributeType instead")]
new public Type GetType() => AttributeType;
#endif
public override string ToString() => AttributeType?.FullName ?? "";
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 COREFX || PROFILE259
Attribute[] all = System.Linq.Enumerable.ToArray(System.Linq.Enumerable.OfType<Attribute>(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;
}
public static AttributeMap[] Create(TypeModel model, MemberInfo member, bool inherit)
{
#if COREFX || PROFILE259
Attribute[] all = System.Linq.Enumerable.ToArray(System.Linq.Enumerable.OfType<Attribute>(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;
}
public static AttributeMap[] Create(TypeModel model, Assembly assembly)
{
#if COREFX || PROFILE259
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;
}
public abstract object Target { get; }
private sealed class ReflectionAttributeMap : AttributeMap
{
private readonly Attribute attribute;
public ReflectionAttributeMap(Attribute attribute)
{
this.attribute = attribute;
}
public override object Target => attribute;
public override Type AttributeType => 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 (string.Equals(member.Name, key, StringComparison.OrdinalIgnoreCase))
{
if (member is PropertyInfo prop) {
value = prop.GetValue(attribute, null);
return true;
}
if (member is FieldInfo field) {
value = field.GetValue(attribute);
return true;
}
throw new NotSupportedException(member.GetType().Name);
}
}
value = null;
return false;
}
}
}
}
#endif

View File

@@ -1,11 +0,0 @@
fileFormatVersion: 2
guid: a3e64de7ef1358447843db562f78060f
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,267 +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] => head[index];
//public object TryGet(int index)
//{
// return head.TryGet(index);
//}
public void Trim() { head = head.Trim(); }
public int Count => head.Length;
IEnumerator IEnumerable.GetEnumerator() => new NodeEnumerator(head);
public NodeEnumerator GetEnumerator() => 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(nameof(index));
}
set
{
if (index >= 0 && index < length)
{
data[index] = value;
}
else
{
throw new ArgumentOutOfRangeException(nameof(index));
}
}
}
//public object TryGet(int index)
//{
// return (index >= 0 && index < length) ? data[index] : null;
//}
private readonly object[] data;
private int length;
public int Length => 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(nameof(keys));
if (values == null) throw new ArgumentNullException(nameof(values));
if (values.Length < keys.Length) throw new ArgumentException("Not all keys are covered by values", nameof(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,11 +0,0 @@
fileFormatVersion: 2
guid: be5fc2a1ac0731a44b0365987d942485
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,110 +0,0 @@
#if !NO_RUNTIME
using System;
using System.Reflection;
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)
{
this.metaType = metaType ?? throw new ArgumentNullException(nameof(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", nameof(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

View File

@@ -1,11 +0,0 @@
fileFormatVersion: 2
guid: de0e7cb7bfcf4904aa31e910f241a8aa
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

File diff suppressed because it is too large Load Diff

View File

@@ -1,11 +0,0 @@
fileFormatVersion: 2
guid: 170c607ac9d3b9346a8f4197e9e4d86a
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,17 +0,0 @@
namespace ProtoBuf.Meta
{
/// <summary>
/// Indiate the variant of the protobuf .proto DSL syntax to use
/// </summary>
public enum ProtoSyntax
{
/// <summary>
/// https://developers.google.com/protocol-buffers/docs/proto
/// </summary>
Proto2 = 0,
/// <summary>
/// https://developers.google.com/protocol-buffers/docs/proto3
/// </summary>
Proto3 = 1,
}
}

View File

@@ -1,11 +0,0 @@
fileFormatVersion: 2
guid: 8df2b30e0bc1f274a8170e86c9d08f96
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

File diff suppressed because it is too large Load Diff

View File

@@ -1,11 +0,0 @@
fileFormatVersion: 2
guid: 0e4440bfa9e92f84d81d48e6c5b0022e
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,97 +0,0 @@
#if !NO_RUNTIME
using System;
using System.Collections.Generic;
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, IComparer<SubType>
{
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 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 => _fieldNumber;
internal set
{
if (_fieldNumber != value)
{
MetaType.AssertValidFieldNumber(value);
ThrowIfFrozen();
_fieldNumber = value;
}
}
}
private void ThrowIfFrozen()
{
if (serializer != null) throw new InvalidOperationException("The type cannot be changed once a serializer has been generated");
}
/// <summary>
/// The sub-type to be considered.
/// </summary>
public MetaType DerivedType => 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(nameof(derivedType));
if (fieldNumber <= 0) throw new ArgumentOutOfRangeException(nameof(fieldNumber));
_fieldNumber = fieldNumber;
this.derivedType = derivedType;
this.dataFormat = format;
}
private readonly DataFormat dataFormat;
private IProtoSerializer serializer;
internal IProtoSerializer Serializer => serializer ?? (serializer = BuildSerializer());
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,11 +0,0 @@
fileFormatVersion: 2
guid: a2912d37917b74846bdcffe3daa174d2
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,33 +0,0 @@
using System;
namespace ProtoBuf.Meta
{
/// <summary>
/// Event data associated with new types being added to a model
/// </summary>
public sealed class TypeAddedEventArgs : EventArgs
{
internal TypeAddedEventArgs(MetaType metaType)
{
MetaType = metaType;
ApplyDefaultBehaviour = true;
}
/// <summary>
/// Whether or not to apply the default mapping behavior
/// </summary>
public bool ApplyDefaultBehaviour { get; set; }
/// <summary>
/// The configuration of the type being added
/// </summary>
public MetaType MetaType { get; }
/// <summary>
/// The type that was added to the model
/// </summary>
public Type Type => MetaType.Type;
/// <summary>
/// The model that is being changed
/// </summary>
public RuntimeTypeModel Model => MetaType.Model as RuntimeTypeModel;
}
}

View File

@@ -1,11 +0,0 @@
fileFormatVersion: 2
guid: 1500030a10d2168408f75fe907ce0568
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,64 +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 (string.IsNullOrEmpty(formattedName)) throw new ArgumentNullException("formattedName");
this.formattedName = formattedName;
// typeFixed = false; <== implicit
}
internal TypeFormatEventArgs(Type type)
{
this.type = type ?? throw new ArgumentNullException(nameof(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);
}

View File

@@ -1,11 +0,0 @@
fileFormatVersion: 2
guid: d27afe6e96660d1418a49cf374e84ad0
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,45 +0,0 @@
using System;
using System.IO;
namespace ProtoBuf.Meta
{
partial class TypeModel :
IProtoInput<Stream>,
IProtoInput<ArraySegment<byte>>,
IProtoInput<byte[]>,
IProtoOutput<Stream>
{
static SerializationContext CreateContext(object userState)
{
if (userState == null)
return SerializationContext.Default;
if (userState is SerializationContext ctx)
return ctx;
var obj = new SerializationContext { Context = userState };
obj.Freeze();
return obj;
}
T IProtoInput<Stream>.Deserialize<T>(Stream source, T value, object userState)
=> (T)Deserialize(source, value, typeof(T), CreateContext(userState));
T IProtoInput<ArraySegment<byte>>.Deserialize<T>(ArraySegment<byte> source, T value, object userState)
{
using (var ms = new MemoryStream(source.Array, source.Offset, source.Count))
{
return (T)Deserialize(ms, value, typeof(T), CreateContext(userState));
}
}
T IProtoInput<byte[]>.Deserialize<T>(byte[] source, T value, object userState)
{
using (var ms = new MemoryStream(source))
{
return (T)Deserialize(ms, value, typeof(T), CreateContext(userState));
}
}
void IProtoOutput<Stream>.Serialize<T>(Stream destination, T value, object userState)
=> Serialize(destination, value, CreateContext(userState));
}
}

View File

@@ -1,11 +0,0 @@
fileFormatVersion: 2
guid: d683bc55be70e8e46824012108beb15f
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

File diff suppressed because it is too large Load Diff

View File

@@ -1,11 +0,0 @@
fileFormatVersion: 2
guid: e5eb182ec8bc8c5469c7819c0e3f7fb4
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,855 +0,0 @@
#if !NO_RUNTIME
using System;
using ProtoBuf.Serializers;
using System.Globalization;
using System.Collections.Generic;
#if PROFILE259
using System.Reflection;
using System.Linq;
#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 int _fieldNumber;
/// <summary>
/// The number that identifies this member in a protobuf stream
/// </summary>
public int FieldNumber
{
get => _fieldNumber;
internal set
{
if (_fieldNumber != value)
{
MetaType.AssertValidFieldNumber(value);
ThrowIfFrozen();
_fieldNumber = value;
}
}
}
private readonly MemberInfo originalMember;
private MemberInfo backingMember;
/// <summary>
/// Gets the member (field/property) which this member relates to.
/// </summary>
public MemberInfo Member { get { return originalMember; } }
/// <summary>
/// Gets the backing member (field/property) which this member relates to
/// </summary>
public MemberInfo BackingMember
{
get { return backingMember; }
set
{
if (backingMember != value)
{
ThrowIfFrozen();
backingMember = value;
}
}
}
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 => itemType;
/// <summary>
/// The underlying type of the member
/// </summary>
public Type MemberType => memberType;
/// <summary>
/// For abstract types (IList etc), the type of concrete object to create (if required)
/// </summary>
public Type DefaultType => defaultType;
/// <summary>
/// The type the defines the member
/// </summary>
public Type ParentType => parentType;
/// <summary>
/// The default value of the item (members with this value will not be serialized)
/// </summary>
public object DefaultValue
{
get { return defaultValue; }
set
{
if (defaultValue != value)
{
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 (parentType == null) throw new ArgumentNullException("parentType");
if (fieldNumber < 1 && !Helpers.IsEnum(parentType)) throw new ArgumentOutOfRangeException("fieldNumber");
this.originalMember = member ?? throw new ArgumentNullException("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)
{
AsReference = type.AsReferenceDefault;
}
else
{ // we need to scan the hard way; can't risk recursion by fully walking it
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)
{
_fieldNumber = fieldNumber;
this.memberType = memberType ?? throw new ArgumentNullException(nameof(memberType));
this.itemType = itemType;
this.defaultType = defaultType;
this.model = model ?? throw new ArgumentNullException(nameof(model));
this.dataFormat = dataFormat;
}
internal object GetRawEnumValue()
{
#if PORTABLE || CF || COREFX || PROFILE259
object value = ((FieldInfo)originalMember).GetValue(null);
switch(Helpers.GetTypeCode(Enum.GetUnderlyingType(((FieldInfo)originalMember).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)originalMember).GetRawConstantValue();
#endif
}
private static object ParseDefaultValue(Type type, object value)
{
{
Type tmp = Helpers.GetUnderlyingType(type);
if (tmp != null) type = tmp;
}
if (value is string s)
{
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 (Helpers.IsEnum(type)) return Enum.ToObject(type, value);
return Convert.ChangeType(value, type, CultureInfo.InvariantCulture);
}
private IProtoSerializer serializer;
internal IProtoSerializer Serializer
{
get
{
return serializer ?? (serializer = BuildSerializer());
}
}
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
{
if (value != dataFormat)
{
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); }
}
/// <summary>
/// Enables full object-tracking/full-graph support.
/// </summary>
public bool AsReference
{
get { return HasFlag(OPTIONS_AsReference); }
set { SetFlag(OPTIONS_AsReference, value, true); }
}
/// <summary>
/// Embeds the type information into the stream, allowing usage with types not known in advance.
/// </summary>
public bool DynamicType
{
get { return HasFlag(OPTIONS_DynamicType); }
set { SetFlag(OPTIONS_DynamicType, value, true); }
}
/// <summary>
/// Indicates that the member should be treated as a protobuf Map
/// </summary>
public bool IsMap
{
get { return HasFlag(OPTIONS_IsMap); }
set { SetFlag(OPTIONS_IsMap, value, true); }
}
private DataFormat mapKeyFormat, mapValueFormat;
/// <summary>
/// Specifies the data-format that should be used for the key, when IsMap is enabled
/// </summary>
public DataFormat MapKeyFormat
{
get { return mapKeyFormat; }
set
{
if (mapKeyFormat != value)
{
ThrowIfFrozen();
mapKeyFormat = value;
}
}
}
/// <summary>
/// Specifies the data-format that should be used for the value, when IsMap is enabled
/// </summary>
public DataFormat MapValueFormat
{
get { return mapValueFormat; }
set
{
if (mapValueFormat != value)
{
ThrowIfFrozen();
mapValueFormat = 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 (this.getSpecified != getSpecified || this.setSpecified != 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");
}
internal bool ResolveMapTypes(out Type dictionaryType, out Type keyType, out Type valueType)
{
dictionaryType = keyType = valueType = null;
try
{
#if COREFX || PROFILE259
var info = memberType.GetTypeInfo();
#else
var info = memberType;
#endif
if (ImmutableCollectionDecorator.IdentifyImmutable(model, MemberType, out _, out _, out _, out _, out _, out _))
{
return false;
}
if (info.IsInterface && info.IsGenericType && info.GetGenericTypeDefinition() == typeof(IDictionary<,>))
{
#if PROFILE259
var typeArgs = memberType.GetGenericTypeDefinition().GenericTypeArguments;
#else
var typeArgs = memberType.GetGenericArguments();
#endif
if (IsValidMapKeyType(typeArgs[0]))
{
keyType = typeArgs[0];
valueType = typeArgs[1];
dictionaryType = memberType;
}
return false;
}
#if PROFILE259
foreach (var iType in memberType.GetTypeInfo().ImplementedInterfaces)
#else
foreach (var iType in memberType.GetInterfaces())
#endif
{
#if COREFX || PROFILE259
info = iType.GetTypeInfo();
#else
info = iType;
#endif
if (info.IsGenericType && info.GetGenericTypeDefinition() == typeof(IDictionary<,>))
{
if (dictionaryType != null) throw new InvalidOperationException("Multiple dictionary interfaces implemented by type: " + memberType.FullName);
#if PROFILE259
var typeArgs = iType.GetGenericTypeDefinition().GenericTypeArguments;
#else
var typeArgs = iType.GetGenericArguments();
#endif
if (IsValidMapKeyType(typeArgs[0]))
{
keyType = typeArgs[0];
valueType = typeArgs[1];
dictionaryType = memberType;
}
}
}
if (dictionaryType == null) return false;
// (note we checked the key type already)
// not a map if value is repeated
Type itemType = null, defaultType = null;
model.ResolveListTypes(valueType, ref itemType, ref defaultType);
if (itemType != null) return false;
return dictionaryType != null;
}
catch
{
// if it isn't a good fit; don't use "map"
return false;
}
}
static bool IsValidMapKeyType(Type type)
{
if (type == null || Helpers.IsEnum(type)) return false;
switch (Helpers.GetTypeCode(type))
{
case ProtoTypeCode.Boolean:
case ProtoTypeCode.Byte:
case ProtoTypeCode.Char:
case ProtoTypeCode.Int16:
case ProtoTypeCode.Int32:
case ProtoTypeCode.Int64:
case ProtoTypeCode.String:
case ProtoTypeCode.SByte:
case ProtoTypeCode.UInt16:
case ProtoTypeCode.UInt32:
case ProtoTypeCode.UInt64:
return true;
}
return false;
}
private IProtoSerializer BuildSerializer()
{
int opaqueToken = 0;
try
{
model.TakeLock(ref opaqueToken);// check nobody is still adding this type
var member = backingMember ?? originalMember;
IProtoSerializer ser;
if (IsMap)
{
ResolveMapTypes(out var dictionaryType, out var keyType, out var valueType);
if (dictionaryType == null)
{
throw new InvalidOperationException("Unable to resolve map type for type: " + memberType.FullName);
}
var concreteType = defaultType;
if (concreteType == null && Helpers.IsClass(memberType))
{
concreteType = memberType;
}
var keySer = TryGetCoreSerializer(model, MapKeyFormat, keyType, out var keyWireType, false, false, false, false);
if (!AsReference)
{
AsReference = MetaType.GetAsReferenceDefault(model, valueType);
}
var valueSer = TryGetCoreSerializer(model, MapValueFormat, valueType, out var valueWireType, AsReference, DynamicType, false, true);
#if PROFILE259
IEnumerable<ConstructorInfo> ctors = typeof(MapDecorator<,,>).MakeGenericType(new Type[] { dictionaryType, keyType, valueType }).GetTypeInfo().DeclaredConstructors;
if (ctors.Count() != 1)
{
throw new InvalidOperationException("Unable to resolve MapDecorator constructor");
}
ser = (IProtoSerializer)ctors.First().Invoke(new object[] {model, concreteType, keySer, valueSer, _fieldNumber,
DataFormat == DataFormat.Group ? WireType.StartGroup : WireType.String, keyWireType, valueWireType, OverwriteList });
#else
var ctors = typeof(MapDecorator<,,>).MakeGenericType(new Type[] { dictionaryType, keyType, valueType }).GetConstructors(
BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);
if (ctors.Length != 1) throw new InvalidOperationException("Unable to resolve MapDecorator constructor");
ser = (IProtoSerializer)ctors[0].Invoke(new object[] {model, concreteType, keySer, valueSer, _fieldNumber,
DataFormat == DataFormat.Group ? WireType.StartGroup : WireType.String, keyWireType, valueWireType, OverwriteList });
#endif
}
else
{
Type finalType = itemType ?? memberType;
ser = TryGetCoreSerializer(model, dataFormat, finalType, out WireType 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)
{
Type underlyingItemType = SupportNull ? itemType : Helpers.GetUnderlyingType(itemType) ?? itemType;
Helpers.DebugAssert(underlyingItemType == ser.ExpectedType
|| (ser.ExpectedType == model.MapType(typeof(object)) && !Helpers.IsValueType(underlyingItemType))
, "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 PORTABLE
else if(memberType.FullName == typeof(Uri).FullName)
{
// In PCLs, the Uri type may not match (WinRT uses Internal/Uri, .Net uses System/Uri)
ser = new ReflectedUriDecorator(memberType, model, ser);
}
#endif
}
if (member != null)
{
if (member is PropertyInfo prop)
{
ser = new PropertyDecorator(model, parentType, prop, ser);
}
else if (member is FieldInfo fld)
{
ser = new FieldDecorator(parentType, fld, 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.WellKnown:
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)
{
{
Type tmp = Helpers.GetUnderlyingType(type);
if (tmp != null) type = tmp;
}
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(dataFormat, 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(dataFormat, model);
case ProtoTypeCode.Guid:
defaultWireType = dataFormat == DataFormat.Group ? WireType.StartGroup : WireType.String;
return new GuidSerializer(model);
case ProtoTypeCode.Uri:
defaultWireType = WireType.String;
return new StringSerializer(model);
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);
MetaType meta = null;
if (key >= 0)
{
meta = model[type];
if (dataFormat == DataFormat.Default && meta.IsGroup)
{
dataFormat = DataFormat.Group;
}
}
if (asReference || dynamicType)
{
BclHelpers.NetObjectOptions options = BclHelpers.NetObjectOptions.None;
if (asReference) options |= BclHelpers.NetObjectOptions.AsReference;
if (dynamicType) options |= BclHelpers.NetObjectOptions.DynamicType;
if (meta != null)
{ // exists
if (asReference && Helpers.IsValueType(type))
{
string message = "AsReference cannot be used with value-types";
if (type.Name == "KeyValuePair`2")
{
message += "; please see https://stackoverflow.com/q/14436606/23354";
}
else
{
message += ": " + type.FullName;
}
throw new InvalidOperationException(message);
}
if (asReference && meta.IsAutoTuple) options |= BclHelpers.NetObjectOptions.LateSet;
if (meta.UseConstructor) options |= BclHelpers.NetObjectOptions.UseConstructor;
}
defaultWireType = dataFormat == DataFormat.Group ? WireType.StartGroup : WireType.String;
return new NetObjectSerializer(model, type, key, options);
}
if (key >= 0)
{
defaultWireType = dataFormat == DataFormat.Group ? WireType.StartGroup : WireType.String;
return new SubItemSerializer(type, key, meta, true);
}
}
defaultWireType = WireType.None;
return null;
}
private string name;
internal void SetName(string name)
{
if (name != this.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 string.IsNullOrEmpty(name) ? originalMember.Name : name; }
set { SetName(value); }
}
private const byte
OPTIONS_IsStrict = 1,
OPTIONS_IsPacked = 2,
OPTIONS_IsRequired = 4,
OPTIONS_OverwriteList = 8,
OPTIONS_SupportNull = 16,
OPTIONS_AsReference = 32,
OPTIONS_IsMap = 64,
OPTIONS_DynamicType = 128;
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 RuntimeTypeModel.CommonImports imports)
{
Type effectiveType = ItemType;
if (effectiveType == null) effectiveType = MemberType;
return model.GetSchemaTypeName(effectiveType, DataFormat, applyNetObjectProxy && AsReference, applyNetObjectProxy && DynamicType, ref imports);
}
internal sealed class Comparer : System.Collections.IComparer, IComparer<ValueMember>
{
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,11 +0,0 @@
fileFormatVersion: 2
guid: dba7fd2d1d1c883469e153f7ac5fdd86
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,190 +0,0 @@
using System;
using System.Collections.Generic;
using ProtoBuf.Meta;
namespace ProtoBuf
{
internal sealed class NetObjectCache
{
internal const int Root = 0;
private MutableList underlyingList;
private MutableList List => underlyingList ?? (underlyingList = new MutableList());
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(nameof(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(nameof(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 (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 Dictionary<object, int>(ReferenceComparer.Default);
index = -1;
}
else
{
if (!objectKeys.TryGetValue(value, out index)) index = -1;
}
#endif
}
else
{
if (stringKeys == null)
{
stringKeys = new Dictionary<string, int>();
index = -1;
}
else
{
if (!stringKeys.TryGetValue(s, out index)) index = -1;
}
}
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;
}
}
}
}
}
private 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 : IEqualityComparer<object>
{
public readonly static ReferenceComparer Default = new ReferenceComparer();
private ReferenceComparer() { }
bool IEqualityComparer<object>.Equals(object x, object y)
{
return x == y; // ref equality
}
int IEqualityComparer<object>.GetHashCode(object obj)
{
return System.Runtime.CompilerServices.RuntimeHelpers.GetHashCode(obj);
}
}
#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,11 +0,0 @@
fileFormatVersion: 2
guid: a7ec59f6037764d43b3d585baf2343e2
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,26 +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 = 0,
/// <summary>
/// A base-128 ("varint", the default prefix format in protobuf) length prefix is applied to the data (efficient for short messages).
/// </summary>
Base128 = 1,
/// <summary>
/// A fixed-length (little-endian) length prefix is applied to the data (useful for compatibility).
/// </summary>
Fixed32 = 2,
/// <summary>
/// A fixed-length (big-endian) length prefix is applied to the data (useful for compatibility).
/// </summary>
Fixed32BigEndian = 3
}
}

View File

@@ -1,11 +0,0 @@
fileFormatVersion: 2
guid: c6f16948bce1f2d4eb805ed31a2bb878
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,175 +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; set; }
/// <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; set; }
/// <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); }
}
/// <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; set; }
/// <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);
}
}
/// <summary>
/// Indicates whether this type should always be treated as a "group" (rather than a string-prefixed sub-message)
/// </summary>
public bool IsGroup
{
get { return HasFlag(OPTIONS_IsGroup); }
set
{
SetFlag(OPTIONS_IsGroup, value);
}
}
private bool HasFlag(ushort flag) { return (flags & flag) == flag; }
private void SetFlag(ushort flag, bool value)
{
if (value) flags |= flag;
else flags = (ushort)(flags & ~flag);
}
private ushort flags;
private const ushort
OPTIONS_InferTagFromName = 1,
OPTIONS_InferTagFromNameHasValue = 2,
OPTIONS_UseProtoMembersOnly = 4,
OPTIONS_SkipConstructor = 8,
OPTIONS_IgnoreListHandling = 16,
OPTIONS_AsReferenceDefault = 32,
OPTIONS_EnumPassthru = 64,
OPTIONS_EnumPassthruHasValue = 128,
OPTIONS_IsGroup = 256;
/// <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>
/// Allows to define a surrogate type used for serialization/deserialization purpose.
/// </summary>
public Type Surrogate { get; set; }
/// <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,11 +0,0 @@
fileFormatVersion: 2
guid: e5d57dba877f0854c999b91a6514d93d
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,13 +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,11 +0,0 @@
fileFormatVersion: 2
guid: 399681000a748834f87d721feda5f459
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,36 +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() => 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; set; }
}
}

View File

@@ -1,11 +0,0 @@
fileFormatVersion: 2
guid: 3b3e030ed91e74b49b87bb0cd9acf139
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,30 +0,0 @@
using System;
#if PLAT_BINARYFORMATTER && !(COREFX || PROFILE259)
using System.Runtime.Serialization;
#endif
namespace ProtoBuf
{
/// <summary>
/// Indicates an error during serialization/deserialization of a proto stream.
/// </summary>
#if PLAT_BINARYFORMATTER && !(COREFX || PROFILE259)
[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 && !(COREFX || PROFILE259)
/// <summary>Creates a new ProtoException instance.</summary>
protected ProtoException(SerializationInfo info, StreamingContext context) : base(info, context) { }
#endif
}
}

View File

@@ -1,11 +0,0 @@
fileFormatVersion: 2
guid: 8629683d41766534fa00bcb5d1a324e0
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,40 +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 (string.IsNullOrEmpty(memberName)) throw new ArgumentNullException(nameof(memberName));
MemberName = memberName;
}
/// <summary>
/// The name of the member to be ignored.
/// </summary>
public string MemberName { get; }
}
}

View File

@@ -1,11 +0,0 @@
fileFormatVersion: 2
guid: b012b09d39a7c2445aba79ffee82b117
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,60 +0,0 @@
using System;
using System.ComponentModel;
using ProtoBuf.Meta;
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, 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(nameof(tag), "Tags must be positive integers");
if (string.IsNullOrEmpty(knownTypeName)) throw new ArgumentNullException(nameof(knownTypeName), "Known type cannot be blank");
Tag = tag;
KnownTypeName = knownTypeName;
}
/// <summary>
/// Gets the unique index (within the type) that will identify this data.
/// </summary>
public int Tag { get; }
/// <summary>
/// Gets the additional type to serialize/deserialize.
/// </summary>
public string KnownTypeName { get; }
/// <summary>
/// Gets the additional type to serialize/deserialize.
/// </summary>
public Type KnownType => 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; set; } = DataFormat.Default;
}
}

View File

@@ -1,11 +0,0 @@
fileFormatVersion: 2
guid: 40d89f2230d5a4f4badf122df4ed9fae
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,29 +0,0 @@
using System;
namespace ProtoBuf
{
/// <summary>
/// Controls the formatting of elements in a dictionary, and indicates that
/// "map" rules should be used: duplicates *replace* earlier values, rather
/// than throwing an exception
/// </summary>
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field)]
public class ProtoMapAttribute : Attribute
{
/// <summary>
/// Describes the data-format used to store the key
/// </summary>
public DataFormat KeyFormat { get; set; }
/// <summary>
/// Describes the data-format used to store the value
/// </summary>
public DataFormat ValueFormat { get; set; }
/// <summary>
/// Disables "map" handling; dictionaries will use ".Add(key,value)" instead of "[key] = value",
/// which means duplicate keys will cause an exception (instead of retaining the final value); if
/// a proto schema is emitted, it will be produced using "repeated" instead of "map"
/// </summary>
public bool DisableMap { get; set; }
}
}

View File

@@ -1,11 +0,0 @@
fileFormatVersion: 2
guid: 2d41a983b561e9043a8ce693aeb9c835
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,228 +0,0 @@
using System;
using System.Reflection;
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
, IComparable<ProtoMemberAttribute>
{
/// <summary>
/// Compare with another ProtoMemberAttribute for sorting purposes
/// </summary>
public int CompareTo(object other) => 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(nameof(tag));
this.tag = tag;
}
#if !NO_RUNTIME
internal MemberInfo Member, BackingMember;
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 !NO_RUNTIME
if (string.IsNullOrEmpty(memberName)) throw new ArgumentNullException(nameof(memberName));
#endif
this.MemberName = memberName;
}
/// <summary>
/// The name of the member to be serialized.
/// </summary>
public string MemberName { get; private set; }
}
}

View File

@@ -1,11 +0,0 @@
fileFormatVersion: 2
guid: 262c0823543b1b3499e2b67ca22f4e62
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

File diff suppressed because it is too large Load Diff

View File

@@ -1,11 +0,0 @@
fileFormatVersion: 2
guid: bd9c8ee218e18b14b9058926b6bbc8fe
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

File diff suppressed because it is too large Load Diff

View File

@@ -1,11 +0,0 @@
fileFormatVersion: 2
guid: 63b2636e44dc3824ca2dbc35316e96ec
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,76 +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 => @default;
#if PLAT_BINARYFORMATTER
#if !(COREFX || PROFILE259)
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 COREFX
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 !(COREFX || PROFILE259)
result.Context = ctx.Context;
result.State = ctx.State;
#endif
return result;
}
#endif
}
}

View File

@@ -1,11 +0,0 @@
fileFormatVersion: 2
guid: 9361aaa524d95b14fbf398ba5bc075a1
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,514 +0,0 @@
using ProtoBuf.Meta;
using System;
using System.IO;
using System.Collections.Generic;
using System.Reflection;
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 static class Serializer
{
#if !NO_RUNTIME
/// <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>() => GetProto<T>(ProtoSyntax.Proto2);
/// <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>(ProtoSyntax syntax)
{
return RuntimeTypeModel.Default.GetSchema(RuntimeTypeModel.Default.MapType(typeof(T)), syntax);
}
/// <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>
/// 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(Type type, Stream source)
{
return RuntimeTypeModel.Default.Deserialize(source, null, type);
}
/// <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 (var ms = new MemoryStream())
{
Serialize<TFrom>(ms, instance);
ms.Position = 0;
return Deserialize<TTo>(ms);
}
}
#if PLAT_BINARYFORMATTER && !(COREFX || PROFILE259)
/// <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(Helpers.GetBuffer(ms), 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 && !(COREFX || PROFILE259)
/// <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
/// <summary>
/// Precompiles the serializer for a given type.
/// </summary>
public static void PrepareSerializer<T>()
{
NonGeneric.PrepareSerializer(typeof(T));
}
#if PLAT_BINARYFORMATTER && !(COREFX || PROFILE259)
/// <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>()
{
return RuntimeTypeModel.Default.CreateFormatter(typeof(T));
}
#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 ignored 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);
}
/// <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)
{
length = ProtoReader.ReadLengthPrefix(source, false, style, out int fieldNumber, out int 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 static class NonGeneric
{
/// <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(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(nameof(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(nameof(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) => RuntimeTypeModel.Default.IsDefined(type);
/// <summary>
/// Precompiles the serializer for a given type.
/// </summary>
public static void PrepareSerializer(Type t)
{
#if FEAT_COMPILER
RuntimeTypeModel model = RuntimeTypeModel.Default;
model[model.MapType(t)].CompileInPlace();
#endif
}
}
/// <summary>
/// Global switches that change the behavior of protobuf-net
/// </summary>
public static class GlobalOptions
{
/// <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();
}
}
}

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