[+] TEngineServer

[+] TEngineServer
This commit is contained in:
ALEXTANG
2023-07-13 17:17:26 +08:00
parent a69f53592e
commit 0c8f3a5f92
790 changed files with 52737 additions and 2533 deletions

View File

@@ -1,63 +0,0 @@
using System;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Security;
namespace ET
{
public struct AsyncETTaskCompletedMethodBuilder
{
// 1. Static Create method.
[DebuggerHidden]
public static AsyncETTaskCompletedMethodBuilder Create()
{
AsyncETTaskCompletedMethodBuilder builder = new AsyncETTaskCompletedMethodBuilder();
return builder;
}
// 2. TaskLike Task property(void)
public ETTaskCompleted Task => default;
// 3. SetException
[DebuggerHidden]
public void SetException(Exception e)
{
ETTask.ExceptionHandler.Invoke(e);
}
// 4. SetResult
[DebuggerHidden]
public void SetResult()
{
// do nothing
}
// 5. AwaitOnCompleted
[DebuggerHidden]
public void AwaitOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : INotifyCompletion where TStateMachine : IAsyncStateMachine
{
awaiter.OnCompleted(stateMachine.MoveNext);
}
// 6. AwaitUnsafeOnCompleted
[DebuggerHidden]
[SecuritySafeCritical]
public void AwaitUnsafeOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : ICriticalNotifyCompletion where TStateMachine : IAsyncStateMachine
{
awaiter.UnsafeOnCompleted(stateMachine.MoveNext);
}
// 7. Start
[DebuggerHidden]
public void Start<TStateMachine>(ref TStateMachine stateMachine) where TStateMachine : IAsyncStateMachine
{
stateMachine.MoveNext();
}
// 8. SetStateMachine
[DebuggerHidden]
public void SetStateMachine(IAsyncStateMachine stateMachine)
{
}
}
}

View File

@@ -1,125 +0,0 @@
using System;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Security;
namespace ET
{
public struct ETAsyncTaskMethodBuilder
{
private ETTask tcs;
// 1. Static Create method.
[DebuggerHidden]
public static ETAsyncTaskMethodBuilder Create()
{
ETAsyncTaskMethodBuilder builder = new ETAsyncTaskMethodBuilder() { tcs = ETTask.Create(true) };
return builder;
}
// 2. TaskLike Task property.
[DebuggerHidden]
public ETTask Task => this.tcs;
// 3. SetException
[DebuggerHidden]
public void SetException(Exception exception)
{
this.tcs.SetException(exception);
}
// 4. SetResult
[DebuggerHidden]
public void SetResult()
{
this.tcs.SetResult();
}
// 5. AwaitOnCompleted
[DebuggerHidden]
public void AwaitOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : INotifyCompletion where TStateMachine : IAsyncStateMachine
{
awaiter.OnCompleted(stateMachine.MoveNext);
}
// 6. AwaitUnsafeOnCompleted
[DebuggerHidden]
[SecuritySafeCritical]
public void AwaitUnsafeOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : ICriticalNotifyCompletion where TStateMachine : IAsyncStateMachine
{
awaiter.OnCompleted(stateMachine.MoveNext);
}
// 7. Start
[DebuggerHidden]
public void Start<TStateMachine>(ref TStateMachine stateMachine) where TStateMachine : IAsyncStateMachine
{
stateMachine.MoveNext();
}
// 8. SetStateMachine
[DebuggerHidden]
public void SetStateMachine(IAsyncStateMachine stateMachine)
{
}
}
public struct ETAsyncTaskMethodBuilder<T>
{
private ETTask<T> tcs;
// 1. Static Create method.
[DebuggerHidden]
public static ETAsyncTaskMethodBuilder<T> Create()
{
ETAsyncTaskMethodBuilder<T> builder = new ETAsyncTaskMethodBuilder<T>() { tcs = ETTask<T>.Create(true) };
return builder;
}
// 2. TaskLike Task property.
[DebuggerHidden]
public ETTask<T> Task => this.tcs;
// 3. SetException
[DebuggerHidden]
public void SetException(Exception exception)
{
this.tcs.SetException(exception);
}
// 4. SetResult
[DebuggerHidden]
public void SetResult(T ret)
{
this.tcs.SetResult(ret);
}
// 5. AwaitOnCompleted
[DebuggerHidden]
public void AwaitOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : INotifyCompletion where TStateMachine : IAsyncStateMachine
{
awaiter.OnCompleted(stateMachine.MoveNext);
}
// 6. AwaitUnsafeOnCompleted
[DebuggerHidden]
[SecuritySafeCritical]
public void AwaitUnsafeOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : ICriticalNotifyCompletion where TStateMachine : IAsyncStateMachine
{
awaiter.OnCompleted(stateMachine.MoveNext);
}
// 7. Start
[DebuggerHidden]
public void Start<TStateMachine>(ref TStateMachine stateMachine) where TStateMachine : IAsyncStateMachine
{
stateMachine.MoveNext();
}
// 8. SetStateMachine
[DebuggerHidden]
public void SetStateMachine(IAsyncStateMachine stateMachine)
{
}
}
}

View File

@@ -1,64 +0,0 @@
using System;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Security;
namespace ET
{
internal struct AsyncETVoidMethodBuilder
{
// 1. Static Create method.
[DebuggerHidden]
public static AsyncETVoidMethodBuilder Create()
{
AsyncETVoidMethodBuilder builder = new AsyncETVoidMethodBuilder();
return builder;
}
// 2. TaskLike Task property(void)
[DebuggerHidden]
public ETVoid Task => default;
// 3. SetException
[DebuggerHidden]
public void SetException(Exception e)
{
ETTask.ExceptionHandler.Invoke(e);
}
// 4. SetResult
[DebuggerHidden]
public void SetResult()
{
// do nothing
}
// 5. AwaitOnCompleted
[DebuggerHidden]
public void AwaitOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : INotifyCompletion where TStateMachine : IAsyncStateMachine
{
awaiter.OnCompleted(stateMachine.MoveNext);
}
// 6. AwaitUnsafeOnCompleted
[DebuggerHidden]
[SecuritySafeCritical]
public void AwaitUnsafeOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : ICriticalNotifyCompletion where TStateMachine : IAsyncStateMachine
{
awaiter.UnsafeOnCompleted(stateMachine.MoveNext);
}
// 7. Start
[DebuggerHidden]
public void Start<TStateMachine>(ref TStateMachine stateMachine) where TStateMachine : IAsyncStateMachine
{
stateMachine.MoveNext();
}
// 8. SetStateMachine
[DebuggerHidden]
public void SetStateMachine(IAsyncStateMachine stateMachine)
{
}
}
}

View File

@@ -1,54 +0,0 @@
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
namespace ET
{
public class ETCancellationToken
{
private HashSet<Action> actions = new HashSet<Action>();
public void Add(Action callback)
{
// 如果action是null绝对不能添加,要抛异常,说明有协程泄漏
this.actions.Add(callback);
}
public void Remove(Action callback)
{
this.actions?.Remove(callback);
}
public bool IsDispose()
{
return this.actions == null;
}
public void Cancel()
{
if (this.actions == null)
{
return;
}
this.Invoke();
}
private void Invoke()
{
HashSet<Action> runActions = this.actions;
this.actions = null;
try
{
foreach (Action action in runActions)
{
action.Invoke();
}
}
catch (Exception e)
{
ETTask.ExceptionHandler.Invoke(e);
}
}
}
}

View File

@@ -1,313 +0,0 @@
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Runtime.ExceptionServices;
namespace ET
{
[AsyncMethodBuilder(typeof (ETAsyncTaskMethodBuilder))]
public class ETTask: ICriticalNotifyCompletion
{
public static Action<Exception> ExceptionHandler;
public static ETTaskCompleted CompletedTask
{
get
{
return new ETTaskCompleted();
}
}
private static readonly ConcurrentQueue<ETTask> queue = new();
/// <summary>
/// 请不要随便使用ETTask的对象池除非你完全搞懂了ETTask!!!
/// 假如开启了池,await之后不能再操作ETTask否则可能操作到再次从池中分配出来的ETTask产生灾难性的后果
/// SetResult的时候请现将tcs置空避免多次对同一个ETTask SetResult
/// </summary>
public static ETTask Create(bool fromPool = false)
{
if (!fromPool)
{
return new ETTask();
}
if (!queue.TryDequeue(out ETTask task))
{
return new ETTask() {fromPool = true};
}
return task;
}
private void Recycle()
{
if (!this.fromPool)
{
return;
}
this.state = AwaiterStatus.Pending;
this.callback = null;
// 太多了
if (queue.Count > 1000)
{
return;
}
queue.Enqueue(this);
}
private bool fromPool;
private AwaiterStatus state;
private object callback; // Action or ExceptionDispatchInfo
private ETTask()
{
}
[DebuggerHidden]
private async ETVoid InnerCoroutine()
{
await this;
}
[DebuggerHidden]
public void Coroutine()
{
InnerCoroutine().Coroutine();
}
[DebuggerHidden]
public ETTask GetAwaiter()
{
return this;
}
public bool IsCompleted
{
[DebuggerHidden]
get
{
return this.state != AwaiterStatus.Pending;
}
}
[DebuggerHidden]
public void UnsafeOnCompleted(Action action)
{
if (this.state != AwaiterStatus.Pending)
{
action?.Invoke();
return;
}
this.callback = action;
}
[DebuggerHidden]
public void OnCompleted(Action action)
{
this.UnsafeOnCompleted(action);
}
[DebuggerHidden]
public void GetResult()
{
switch (this.state)
{
case AwaiterStatus.Succeeded:
this.Recycle();
break;
case AwaiterStatus.Faulted:
ExceptionDispatchInfo c = this.callback as ExceptionDispatchInfo;
this.callback = null;
this.Recycle();
c?.Throw();
break;
default:
throw new NotSupportedException("ETTask does not allow call GetResult directly when task not completed. Please use 'await'.");
}
}
[DebuggerHidden]
public void SetResult()
{
if (this.state != AwaiterStatus.Pending)
{
throw new InvalidOperationException("TaskT_TransitionToFinal_AlreadyCompleted");
}
this.state = AwaiterStatus.Succeeded;
Action c = this.callback as Action;
this.callback = null;
c?.Invoke();
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[DebuggerHidden]
public void SetException(Exception e)
{
if (this.state != AwaiterStatus.Pending)
{
throw new InvalidOperationException("TaskT_TransitionToFinal_AlreadyCompleted");
}
this.state = AwaiterStatus.Faulted;
Action c = this.callback as Action;
this.callback = ExceptionDispatchInfo.Capture(e);
c?.Invoke();
}
}
[AsyncMethodBuilder(typeof (ETAsyncTaskMethodBuilder<>))]
public class ETTask<T>: ICriticalNotifyCompletion
{
private static readonly ConcurrentQueue<ETTask<T>> queue = new();
/// <summary>
/// 请不要随便使用ETTask的对象池除非你完全搞懂了ETTask!!!
/// 假如开启了池,await之后不能再操作ETTask否则可能操作到再次从池中分配出来的ETTask产生灾难性的后果
/// SetResult的时候请现将tcs置空避免多次对同一个ETTask SetResult
/// </summary>
public static ETTask<T> Create(bool fromPool = false)
{
if (!fromPool)
{
return new ETTask<T>();
}
if (!queue.TryDequeue(out ETTask<T> task))
{
return new ETTask<T>() {fromPool = true};
}
return task;
}
private void Recycle()
{
if (!this.fromPool)
{
return;
}
this.callback = null;
this.value = default;
this.state = AwaiterStatus.Pending;
// 太多了
if (queue.Count > 1000)
{
return;
}
queue.Enqueue(this);
}
private bool fromPool;
private AwaiterStatus state;
private T value;
private object callback; // Action or ExceptionDispatchInfo
private ETTask()
{
}
[DebuggerHidden]
private async ETVoid InnerCoroutine()
{
await this;
}
[DebuggerHidden]
public void Coroutine()
{
InnerCoroutine().Coroutine();
}
[DebuggerHidden]
public ETTask<T> GetAwaiter()
{
return this;
}
[DebuggerHidden]
public T GetResult()
{
switch (this.state)
{
case AwaiterStatus.Succeeded:
T v = this.value;
this.Recycle();
return v;
case AwaiterStatus.Faulted:
ExceptionDispatchInfo c = this.callback as ExceptionDispatchInfo;
this.callback = null;
this.Recycle();
c?.Throw();
return default;
default:
throw new NotSupportedException("ETask does not allow call GetResult directly when task not completed. Please use 'await'.");
}
}
public bool IsCompleted
{
[DebuggerHidden]
get
{
return state != AwaiterStatus.Pending;
}
}
[DebuggerHidden]
public void UnsafeOnCompleted(Action action)
{
if (this.state != AwaiterStatus.Pending)
{
action?.Invoke();
return;
}
this.callback = action;
}
[DebuggerHidden]
public void OnCompleted(Action action)
{
this.UnsafeOnCompleted(action);
}
[DebuggerHidden]
public void SetResult(T result)
{
if (this.state != AwaiterStatus.Pending)
{
throw new InvalidOperationException("TaskT_TransitionToFinal_AlreadyCompleted");
}
this.state = AwaiterStatus.Succeeded;
this.value = result;
Action c = this.callback as Action;
this.callback = null;
c?.Invoke();
}
[DebuggerHidden]
public void SetException(Exception e)
{
if (this.state != AwaiterStatus.Pending)
{
throw new InvalidOperationException("TaskT_TransitionToFinal_AlreadyCompleted");
}
this.state = AwaiterStatus.Faulted;
Action c = this.callback as Action;
this.callback = ExceptionDispatchInfo.Capture(e);
c?.Invoke();
}
}
}

View File

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

View File

@@ -1,34 +0,0 @@
using System;
using System.Diagnostics;
using System.Runtime.CompilerServices;
namespace ET
{
[AsyncMethodBuilder(typeof (AsyncETTaskCompletedMethodBuilder))]
public struct ETTaskCompleted: ICriticalNotifyCompletion
{
[DebuggerHidden]
public ETTaskCompleted GetAwaiter()
{
return this;
}
[DebuggerHidden]
public bool IsCompleted => true;
[DebuggerHidden]
public void GetResult()
{
}
[DebuggerHidden]
public void OnCompleted(Action continuation)
{
}
[DebuggerHidden]
public void UnsafeOnCompleted(Action continuation)
{
}
}
}

View File

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

View File

@@ -1,126 +0,0 @@
using System;
using System.Collections.Generic;
namespace ET
{
public static class ETTaskHelper
{
public static bool IsCancel(this ETCancellationToken self)
{
if (self == null)
{
return false;
}
return self.IsDispose();
}
private class CoroutineBlocker
{
private int count;
private ETTask tcs;
public CoroutineBlocker(int count)
{
this.count = count;
}
public async ETTask RunSubCoroutineAsync(ETTask task)
{
try
{
await task;
}
finally
{
--this.count;
if (this.count <= 0 && this.tcs != null)
{
ETTask t = this.tcs;
this.tcs = null;
t.SetResult();
}
}
}
public async ETTask WaitAsync()
{
if (this.count <= 0)
{
return;
}
this.tcs = ETTask.Create(true);
await tcs;
}
}
public static async ETTask WaitAny(List<ETTask> tasks)
{
if (tasks.Count == 0)
{
return;
}
CoroutineBlocker coroutineBlocker = new CoroutineBlocker(1);
foreach (ETTask task in tasks)
{
coroutineBlocker.RunSubCoroutineAsync(task).Coroutine();
}
await coroutineBlocker.WaitAsync();
}
public static async ETTask WaitAny(ETTask[] tasks)
{
if (tasks.Length == 0)
{
return;
}
CoroutineBlocker coroutineBlocker = new CoroutineBlocker(1);
foreach (ETTask task in tasks)
{
coroutineBlocker.RunSubCoroutineAsync(task).Coroutine();
}
await coroutineBlocker.WaitAsync();
}
public static async ETTask WaitAll(ETTask[] tasks)
{
if (tasks.Length == 0)
{
return;
}
CoroutineBlocker coroutineBlocker = new CoroutineBlocker(tasks.Length);
foreach (ETTask task in tasks)
{
coroutineBlocker.RunSubCoroutineAsync(task).Coroutine();
}
await coroutineBlocker.WaitAsync();
}
public static async ETTask WaitAll(List<ETTask> tasks)
{
if (tasks.Count == 0)
{
return;
}
CoroutineBlocker coroutineBlocker = new CoroutineBlocker(tasks.Count);
foreach (ETTask task in tasks)
{
coroutineBlocker.RunSubCoroutineAsync(task).Coroutine();
}
await coroutineBlocker.WaitAsync();
}
}
}

View File

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

View File

@@ -1,28 +0,0 @@
using System;
using System.Diagnostics;
using System.Runtime.CompilerServices;
namespace ET
{
[AsyncMethodBuilder(typeof (AsyncETVoidMethodBuilder))]
internal struct ETVoid: ICriticalNotifyCompletion
{
[DebuggerHidden]
public void Coroutine()
{
}
[DebuggerHidden]
public bool IsCompleted => true;
[DebuggerHidden]
public void OnCompleted(Action continuation)
{
}
[DebuggerHidden]
public void UnsafeOnCompleted(Action continuation)
{
}
}
}

View File

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

View File

@@ -1,14 +0,0 @@
namespace ET
{
public enum AwaiterStatus: byte
{
/// <summary>The operation has not yet completed.</summary>
Pending = 0,
/// <summary>The operation completed successfully.</summary>
Succeeded = 1,
/// <summary>The operation completed with an error.</summary>
Faulted = 2,
}
}

View File

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

View File

@@ -1,5 +1,5 @@
fileFormatVersion: 2
guid: 618c9dd369f43e84296ac09b6f468e9d
guid: 6ec9cf984eeccbb4ba7470e5beeac5a1
folderAsset: yes
DefaultImporter:
externalObjects: {}

View File

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

View File

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

View File

@@ -0,0 +1,33 @@
fileFormatVersion: 2
guid: 95cef76c7e8fc924594a2c535022c037
PluginImporter:
externalObjects: {}
serializedVersion: 2
iconMap: {}
executionOrder: {}
defineConstraints: []
isPreloaded: 0
isOverridable: 0
isExplicitlyReferenced: 0
validateReferences: 1
platformData:
- first:
Android: Android
second:
enabled: 1
settings:
CPU: ARM64
- first:
Any:
second:
enabled: 0
settings: {}
- first:
Editor: Editor
second:
enabled: 0
settings:
DefaultValueInitialized: true
userData:
assetBundleName:
assetBundleVariant:

View File

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

View File

@@ -0,0 +1,33 @@
fileFormatVersion: 2
guid: 1f628c9d6f9d08f40ace37fb91786108
PluginImporter:
externalObjects: {}
serializedVersion: 2
iconMap: {}
executionOrder: {}
defineConstraints: []
isPreloaded: 0
isOverridable: 0
isExplicitlyReferenced: 0
validateReferences: 1
platformData:
- first:
Android: Android
second:
enabled: 1
settings:
CPU: ARMv7
- first:
Any:
second:
enabled: 0
settings: {}
- first:
Editor: Editor
second:
enabled: 0
settings:
DefaultValueInitialized: true
userData:
assetBundleName:
assetBundleVariant:

View File

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

Binary file not shown.

View File

@@ -0,0 +1,33 @@
fileFormatVersion: 2
guid: 618bbca818d51974ea5aaf2c99cbeb25
PluginImporter:
externalObjects: {}
serializedVersion: 2
iconMap: {}
executionOrder: {}
defineConstraints: []
isPreloaded: 0
isOverridable: 0
isExplicitlyReferenced: 0
validateReferences: 1
platformData:
- first:
Android: Android
second:
enabled: 1
settings:
CPU: x86
- first:
Any:
second:
enabled: 0
settings: {}
- first:
Editor: Editor
second:
enabled: 0
settings:
DefaultValueInitialized: true
userData:
assetBundleName:
assetBundleVariant:

View File

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

Binary file not shown.

View File

@@ -0,0 +1,33 @@
fileFormatVersion: 2
guid: 0c70323b22bc343ff88a9509c7355d2e
PluginImporter:
externalObjects: {}
serializedVersion: 2
iconMap: {}
executionOrder: {}
defineConstraints: []
isPreloaded: 0
isOverridable: 0
isExplicitlyReferenced: 0
validateReferences: 1
platformData:
- first:
Any:
second:
enabled: 0
settings: {}
- first:
Editor: Editor
second:
enabled: 0
settings:
DefaultValueInitialized: true
- first:
iPhone: iOS
second:
enabled: 1
settings:
AddToEmbeddedBinaries: false
userData:
assetBundleName:
assetBundleVariant:

View File

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

View File

@@ -0,0 +1,33 @@
fileFormatVersion: 2
guid: 06130465dd5c3436fa423fd696d85760
PluginImporter:
externalObjects: {}
serializedVersion: 2
iconMap: {}
executionOrder: {}
defineConstraints: []
isPreloaded: 0
isOverridable: 0
isExplicitlyReferenced: 0
validateReferences: 1
platformData:
- first:
Any:
second:
enabled: 0
settings: {}
- first:
Editor: Editor
second:
enabled: 1
settings:
DefaultValueInitialized: true
- first:
Standalone: OSXUniversal
second:
enabled: 1
settings:
CPU: AnyCPU
userData:
assetBundleName:
assetBundleVariant:

View File

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

View File

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

View File

@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: 72dcdf060ecf34d279acdee20e77b200
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

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

Binary file not shown.

View File

@@ -0,0 +1,52 @@
fileFormatVersion: 2
guid: 07d3660260d3a4e46944eeb95bb82783
PluginImporter:
externalObjects: {}
serializedVersion: 2
iconMap: {}
executionOrder: {}
defineConstraints: []
isPreloaded: 0
isOverridable: 0
isExplicitlyReferenced: 0
validateReferences: 1
platformData:
- first:
Any:
second:
enabled: 1
settings: {}
- first:
Editor: Editor
second:
enabled: 0
settings:
CPU: x86_64
DefaultValueInitialized: true
- first:
Standalone: Linux64
second:
enabled: 1
settings:
CPU: x86_64
- first:
Standalone: OSXUniversal
second:
enabled: 1
settings:
CPU: x86_64
- first:
Standalone: Win
second:
enabled: 0
settings:
CPU: None
- first:
Standalone: Win64
second:
enabled: 1
settings:
CPU: x86_64
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,8 +0,0 @@
namespace ET
{
internal struct AckItem
{
internal uint serialNumber;
internal uint timestamp;
}
}

View File

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

View File

@@ -1,23 +0,0 @@
namespace ET
{
public partial class Kcp
{
public const int OneM = 1024 * 1024;
public const int InnerMaxWaitSize = 1024 * 1024;
public const int OuterMaxWaitSize = 1024 * 1024;
public struct SegmentHead
{
public uint conv;
public byte cmd;
public byte frg;
public ushort wnd;
public uint ts;
public uint sn;
public uint una;
public uint len;
}
}
}

View File

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

View File

@@ -1,51 +0,0 @@
// Pool to avoid allocations (from libuv2k & Mirror)
using System;
using System.Buffers;
using System.Collections.Generic;
namespace ET
{
public class Pool<T>
{
// Mirror is single threaded, no need for concurrent collections
readonly Stack<T> objects = new Stack<T>();
// some types might need additional parameters in their constructor, so
// we use a Func<T> generator
readonly Func<T> objectGenerator;
// some types might need additional cleanup for returned objects
readonly Action<T> objectResetter;
public Pool(Func<T> objectGenerator, Action<T> objectResetter, int initialCapacity)
{
this.objectGenerator = objectGenerator;
this.objectResetter = objectResetter;
// allocate an initial pool so we have fewer (if any)
// allocations in the first few frames (or seconds).
for (int i = 0; i < initialCapacity; ++i)
objects.Push(objectGenerator());
}
// take an element from the pool, or create a new one if empty
public T Take() => objects.Count > 0 ? objects.Pop() : objectGenerator();
// return an element to the pool
public void Return(T item)
{
if (this.Count > 1000)
{
return;
}
objectResetter(item);
objects.Push(item);
}
// clear the pool
public void Clear() => objects.Clear();
// count to see how many objects are in the pool. useful for tests.
public int Count => objects.Count;
}
}

View File

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

View File

@@ -1,132 +0,0 @@
using System;
using System.Buffers;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace ET
{
// KCP Segment Definition
internal struct SegmentStruct:IDisposable
{
public Kcp.SegmentHead SegHead;
public uint resendts;
public int rto;
public uint fastack;
public uint xmit;
private byte[] buffer;
private ArrayPool<byte> arrayPool;
public bool IsNull => this.buffer == null;
public int WrittenCount
{
get => (int) this.SegHead.len;
private set => this.SegHead.len = (uint) value;
}
public Span<byte> WrittenBuffer => this.buffer.AsSpan(0, (int) this.SegHead.len);
public Span<byte> FreeBuffer => this.buffer.AsSpan(WrittenCount);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public SegmentStruct(int size, ArrayPool<byte> arrayPool)
{
this.arrayPool = arrayPool;
buffer = arrayPool.Rent(size);
this.SegHead = new Kcp.SegmentHead() { len = 0 };
this.SegHead = default;
this.resendts = default;
this.rto = default;
this.fastack = default;
this.xmit = default;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Encode(Span<byte> data, ref int size)
{
Unsafe.WriteUnaligned(ref MemoryMarshal.GetReference(data),this.SegHead);
size += Unsafe.SizeOf<Kcp.SegmentHead>();
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Advance(int count)
{
this.WrittenCount += count;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Dispose()
{
arrayPool.Return(this.buffer);
}
}
// internal class Segment
// {
// internal uint conv; // conversation
// internal byte cmd; // command, e.g. Kcp.CMD_ACK etc.
// // fragment (sent as 1 byte).
// // 0 if unfragmented, otherwise fragment numbers in reverse: N,..,32,1,0
// // this way the first received segment tells us how many fragments there are.
// internal byte frg;
// internal ushort wnd; // window size that the receive can currently receive
// internal uint ts; // timestamp
// internal uint sn; // sequence number
// internal uint una;
// internal uint resendts; // resend timestamp
// internal int rto;
// internal uint fastack;
// internal uint xmit; // retransmit count
//
// internal MemoryStream data = new MemoryStream(Kcp.MTU_DEF);
//
// [MethodImpl(MethodImplOptions.AggressiveInlining)]
// internal int Encode(byte[] ptr, int offset)
// {
// int previousPosition = offset;
//
// var segHead = new Kcp.SegmentHead()
// {
// conv = this.conv,
// cmd = (byte) this.cmd,
// frg = (byte) frg,
// wnd = (ushort) this.wnd,
// ts = this.ts,
// sn = this.sn,
// una = this.una,
// len = (uint) this.data.Position,
// };
//
// Unsafe.WriteUnaligned(ref MemoryMarshal.GetReference(ptr.AsSpan(offset)),segHead);
// offset+=Unsafe.SizeOf<Kcp.SegmentHead>();
//
// int written = offset - previousPosition;
// return written;
// }
//
// // reset to return a fresh segment to the pool
// [MethodImpl(MethodImplOptions.AggressiveInlining)]
// internal void Reset()
// {
// conv = 0;
// cmd = 0;
// frg = 0;
// wnd = 0;
// ts = 0;
// sn = 0;
// una = 0;
// rto = 0;
// xmit = 0;
// resendts = 0;
// fastack = 0;
//
// // keep buffer for next pool usage, but reset length (= bytes written)
// data.SetLength(0);
// }
// }
}

View File

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

View File

@@ -1,106 +0,0 @@
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace ET
{
public static partial class Utils
{
// Clamp so we don't have to depend on UnityEngine
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static int Clamp(int value, int min, int max)
{
if (value < min) return min;
if (value > max) return max;
return value;
}
// // encode 8 bits unsigned int
// [MethodImpl(MethodImplOptions.AggressiveInlining)]
// public static int Encode8u(byte[] p, int offset, byte value)
// {
// p[0 + offset] = value;
// return 1;
// }
//
// // decode 8 bits unsigned int
// [MethodImpl(MethodImplOptions.AggressiveInlining)]
// public static int Decode8u(byte[] p, int offset, out byte value)
// {
// value = p[0 + offset];
// return 1;
// }
//
// [MethodImpl(MethodImplOptions.AggressiveInlining)]
// public static int Decode8u(ReadOnlySpan<byte> data,int offset,out byte value)
// {
// value = data[offset];
// return 1;
// }
//
// // encode 16 bits unsigned int (lsb)
// [MethodImpl(MethodImplOptions.AggressiveInlining)]
// public static int Encode16U(byte[] p, int offset, ushort value)
// {
// p[0 + offset] = (byte)(value >> 0);
// p[1 + offset] = (byte)(value >> 8);
// return 2;
// }
//
// // decode 16 bits unsigned int (lsb)
// [MethodImpl(MethodImplOptions.AggressiveInlining)]
// public static int Decode16U(byte[] p, int offset, out ushort value)
// {
// ushort result = 0;
// result |= p[0 + offset];
// result |= (ushort)(p[1 + offset] << 8);
// value = result;
// return 2;
// }
//
// [MethodImpl(MethodImplOptions.AggressiveInlining)]
// public static int Decode16U(ReadOnlySpan<byte> data, int offset, out ushort value)
// {
// value = Unsafe.ReadUnaligned<ushort>(ref MemoryMarshal.GetReference(data.Slice(offset)));
// return 2;
// }
//
// // encode 32 bits unsigned int (lsb)
// [MethodImpl(MethodImplOptions.AggressiveInlining)]
// public static int Encode32U(byte[] p, int offset, uint value)
// {
// p[0 + offset] = (byte)(value >> 0);
// p[1 + offset] = (byte)(value >> 8);
// p[2 + offset] = (byte)(value >> 16);
// p[3 + offset] = (byte)(value >> 24);
// return 4;
// }
//
// // decode 32 bits unsigned int (lsb)
// [MethodImpl(MethodImplOptions.AggressiveInlining)]
// public static int Decode32U(byte[] p, int offset, out uint value)
// {
// uint result = 0;
// result |= p[0 + offset];
// result |= (uint)(p[1 + offset] << 8);
// result |= (uint)(p[2 + offset] << 16);
// result |= (uint)(p[3 + offset] << 24);
// value = result;
// return 4;
// }
//
// [MethodImpl(MethodImplOptions.AggressiveInlining)]
// public static int Decode32U(ReadOnlySpan<byte> data, int offset, out uint value)
// {
// value = Unsafe.ReadUnaligned<uint>(ref MemoryMarshal.GetReference(data.Slice(offset)));
// return 4;
// }
// timediff was a macro in original Kcp. let's inline it if possible.
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static int TimeDiff(uint later, uint earlier)
{
return (int)(later - earlier);
}
}
}

View File

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

View File

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

View File

@@ -0,0 +1,712 @@
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,5 +1,5 @@
fileFormatVersion: 2
guid: 841f2f7b2ba44e24689645e00f9ed245
guid: 5072fbed211eb9f43a3cd2805dd75ef7
MonoImporter:
externalObjects: {}
serializedVersion: 2

View File

@@ -0,0 +1,78 @@
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,5 +1,5 @@
fileFormatVersion: 2
guid: a61c2db12429afb40b78a3f953e46510
guid: a9cf66041a027e94892d5014c2b905b3
MonoImporter:
externalObjects: {}
serializedVersion: 2

View File

@@ -0,0 +1,149 @@
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,5 +1,5 @@
fileFormatVersion: 2
guid: bf2682587b9394aa89238524a4ef1ef9
guid: 423b228ed060b91458bc6d4e6aa0f570
MonoImporter:
externalObjects: {}
serializedVersion: 2

View File

@@ -0,0 +1,33 @@
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,5 +1,5 @@
fileFormatVersion: 2
guid: 9a7cde4b1a6c34b49a309698cdfb233f
guid: 53de2cb3784c9dd43aa6f30d7df072a4
MonoImporter:
externalObjects: {}
serializedVersion: 2

View File

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

File diff suppressed because it is too large Load Diff

View File

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

View File

@@ -0,0 +1,7 @@
#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

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

View File

@@ -0,0 +1,58 @@
#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

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

View File

@@ -0,0 +1,49 @@

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

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

View File

@@ -0,0 +1,176 @@
#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

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

View File

@@ -0,0 +1,416 @@
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

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

View File

@@ -0,0 +1,284 @@
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

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

View File

@@ -0,0 +1,118 @@
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

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

Binary file not shown.

View File

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

View File

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

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

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

View File

@@ -0,0 +1,23 @@

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

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

View File

@@ -0,0 +1,58 @@

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

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

View File

@@ -0,0 +1,13 @@
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

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

View File

@@ -0,0 +1,55 @@
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

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

View File

@@ -0,0 +1,29 @@
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

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

View File

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

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

View File

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

View File

@@ -0,0 +1,108 @@
#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

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

View File

@@ -0,0 +1,267 @@
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

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

View File

@@ -0,0 +1,110 @@
#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

@@ -0,0 +1,11 @@
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

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

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